How do I filter query objects by date range in Django?

后端 未结 7 1524
执念已碎
执念已碎 2020-11-22 16:02

I\'ve got a field in one model like:

class Sample(models.Model):
    date = fields.DateField(auto_now=False)

Now, I need to filter the obje

7条回答
  •  名媛妹妹
    2020-11-22 16:38

    You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:

    start = date(2012, 12, 11)
    end = date(2012, 12, 18)
    new_end = end + datetime.timedelta(days=1)
    
    ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])
    

    As discussed previously, without doing something like this, records are ignored on the last day.

    Edited to avoid the use of datetime.combine -- seems more logical to stick with date instances when comparing against a DateTimeField, instead of messing about with throwaway (and confusing) datetime objects. See further explanation in comments below.

提交回复
热议问题