3

I need to filter another datetime field through a datetime field, but I just need to compare date. How to implement it by F expression?

F expression does not seem to format fields

My model is:

class Test():
   date1 = models.DateTimeField()
   date2 = models.DateTimeField()

I just need to compare date, not time.

Test.objects.filter(Q(date2__gt=F('date1')))

It keeps comparing datetime. That's not what I want. I just want to compare date. As a Django rookie, I can't find a solution.
I used time zone and Mysql, and I don't want to modify them.

Scheinin
  • 195
  • 9
  • Possible duplicate of [Django F expression on datetime objects](https://stackoverflow.com/questions/43890131/django-f-expression-on-datetime-objects) – imposeren May 15 '19 at 07:13

1 Answers1

1

You can use the __date field lookup for this.

In your case:

Test.objects.filter(Q(date2__date__gt=F('date1__date')))

Can give you the desired result.

The __date field lookup helps to extract only the date from the datetime field.

But make sure that you are using Django>1.9, for older versions of Django, you need to use other methods

Sanip
  • 1,772
  • 1
  • 14
  • 29
  • `F('date1__date')` is not supported until Django-2.2. And also this question is a duplicate of: https://stackoverflow.com/questions/43890131/django-f-expression-on-datetime-objects – imposeren May 15 '19 at 07:15
  • @imposeren can you please provide the reference for your statement? I have used `F('date1__date')` in Django 2.1 for cross checking too. Can you explain how it was possible? – Sanip May 15 '19 at 07:30
  • I'm sorry, looks like I confused it with "QuerySet.order_by() and distinct(*fields) now support using field transforms.". But still for some reason it's not working inside of `F-expression` on one of my projects using django 2.0.11... Strange. – imposeren May 15 '19 at 08:34
  • I did test it before posting this answer. :) Also this question is not a duplicate as the OP requires to filter the queryset on basis of 'date' rather than 'year', 'second' or 'month'. – Sanip May 15 '19 at 08:38
  • 1
    Thanks guys, `__date` doesn't work for me because I need to use the time zone and Mysql, and I don't want to modify the database. – Scheinin May 16 '19 at 01:15