[Django]-Django query is it possible to use self

4👍

Yes, given date_from and date_to are fiels, you can use an F-expression [Django-doc] to reference to another column:

from django.db.models import F

myvar = MyModel.objects.exclude(date_from=F('date_to'))

The F-expression here thus contains a string, and acts as a “representative” of the field. Here we thus will obtain all MyModels where the two columns date_from and date_to are different.

This will thus result in a query that looks more or less like:

SELECT mymodel.*
FROM mymodel
WHERE NOT(date_from = date_to)

(Django normally mentions all the fields it selects explicitly, this is more to show that the filtering will be done at the database level)

Leave a comment