假设我们有一个Driver模型,而Driver可能拥有很多车。我希望能够过滤QuerySet
,以便能够看到驾驶特定车辆的所有司机。即:
class Driver(models.Model):
primary_car = models.ForeignKey(Car, related_name='primary')
cars = models.ManyToMany(Car, related_name = 'all')
def save(self, force_insert=False, force_update=False, using=None, *args, **kwargs):
if self.primary_car not in self.cars.all():
self.cars.add(self.primary_car)
super(Car, self).save(force_insert=False, force_update=False, using=None, *args, **kwargs)
class Car(models.Models):
name = models.CharField(max_length=30)
所以,假设我有50名司机,而且我知道7名有Yugos,而2名有Yugos作为他们的主要赛车。如何搜索这些驱动程序?我认为只需不到2分钟的谷歌搜索即可找到这个答案,所以我可能会遗漏一些基本的东西。
更新:我修复了损坏的save()
方法
答案 0 :(得分:2)
from django.db.models import Q
# drivers who have either have a "Yugo" as their primary car,
# or have a relation to one
yugo_drivers = Driver.objects.filter(Q(primary_car__name__iexact="Yugo") |
Q(cars__name__iexact="Yugo"))
有两件事可以帮助你:
答案 1 :(得分:0)
qs = Driver.objects.filter(Car_name=your_car.name)