简体   繁体   English

django:当2个字段具有相同值时过滤queryset

[英]django: filter queryset when 2 fields have same value

I have a model which has 2 fields like, 我有一个模型,其中包含2个字段,

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, 我想要admin中的过滤器,该过滤器可以根据以下内容过滤查询集:

  • pickup and drop ids are different 提取和放置ID不同
  • pickup and drop ids are same 提取和放置ID相同

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] . 你可以参考A F ieldF -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 q uery by using a Q -object [Django-doc] : 我们可以通过使用否定 A Q uery 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. 这里的波浪号( ~ )表示我们否定Q对象表示的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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