1

假设我们有一个 Driver 模型,一个 Driver 可能拥有许多汽车。我希望能够过滤 aQuerySet以便我可以看到所有驾驶特定汽车的司机。IE:

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()方法

4

2 回答 2

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"))

有两件事可以帮助您:

于 2013-02-26T18:45:56.007 回答
0
qs = Driver.objects.filter(Car_name=your_car.name)
于 2013-02-26T18:45:57.103 回答