简体   繁体   中英

django: filter queryset when 2 fields have same value

I have a model which has 2 fields like,

pickup_station_id = models.IntegerField(null=True)
drop_station_id = models.IntegerField(null=True)

I want a filter in admin which can filter the queryset based on,

  • pickup and drop ids are different
  • pickup and drop ids are same

How can I get a queryset based on these conditions?

I mean, something like this,

Mymodel.objects.filter(pickup_station_id==drop_station_id)

Mymodel.objects.filter(pickup_station_id!=drop_station_id)

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

from django.db.models import 

Mymodel.objects.filter(pickup_station_id=)

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

from django.db.models import F, 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM