Home > Mobile >  How do I write a Django query that matches only the minute field of a DateTime column?
How do I write a Django query that matches only the minute field of a DateTime column?

Time:11-01

I'm using Django 3.2 and PostGres 9.6. I have this model with a "created" DateTime field ...

class PriceQuote(models.Model):
        ...
    created = models.DateTimeField(null=False, default=datetime.now)

How do I write a Django filter query that includes a clause to match the minute field of the created column? So in the below

class PriceQuoteManager():
    def get_prices_per_hour(self, item):
        now = datetime.datetime.now()
        end_time = now.replace(second = 0, microsecond = 0)
        start_time = end_time - timedelta(days=1)
        return PriceQuote.objects.filter(
            item=item,
            created__range=[start_time, end_time],
            xxx=end_time.minute
        )

I want to replace "xxx" with a clause that says match the minute field of "created" with the minute field of the "end_time" variable.

CodePudding user response:

You can use __minute:

        return PriceQuote.objects.filter(
            item=item,
            created__range=[start_time, end_time],
            created__minute=end_time.minute
        )
  • Related