[Django]-Django: filter queryset when 2 fields have same value

10👍

You can refer to a field with an F-expression [Django-doc]. So we can write it like:

from django.db.models import F

Mymodel.objects.filter(pickup_station_id=F('drop_station_id'))

We can negate a query by using a Q-object [Django-doc]:

from django.db.models import F, Q

Mymodel.objects.filter(~Q(pickup_station_id=F('drop_station_id')))

Here the tilde (~) means we negate the condition that the Q object represents.

Leave a comment