Cole
Cole

Reputation: 2509

Django filtering by a value which might be in a many-to-many field

Lets say we have a Driver model, and a Driver might own many cars. I want to be able to filter a QuerySet so that I can see all the drivers who drive a specific car. I.e:

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)

So let's say I have 50 drivers, and I know that 7 have Yugos and that 2 have Yugos as their primary car. How do I search for these drivers? I thought it would take less than 2 minutes of googling to find this answer, so I'm probably missing something basic.

UPDATE: I fixed the mangled save() method

Upvotes: 1

Views: 72

Answers (2)

Matt
Matt

Reputation: 10312

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

Two things that will help you out are:

Upvotes: 2

Gustavo Reyes
Gustavo Reyes

Reputation: 1344

qs = Driver.objects.filter(Car_name=your_car.name)

Upvotes: 0

Related Questions