Dmitrii Mikhailov
Dmitrii Mikhailov

Reputation: 5241

How to filter for ManyToMany that contains object

I have objects like these:

class Pencil(models.Model):
    color = models.CharField(max_length=20, unique=True)

class Box(models.Model):
   pencils = models.ManyToManyField(Pencil)
   name = models.CharField(max_length=50)

let's say that I have a pencil with blue color:

pencil = Pencil.objects.create(color='blue')

and then I create some instances of Box class. And then I'm doing some filtering by name

boxes = Box.objects.filter(name__startswith='Big')

How can I filter further to get only boxes that have name starting from "Big" and that have a pencil with blue color ? I cannot do something like pencil.box_set.all() because I've already did some filtering on boxes.

Upvotes: 2

Views: 61

Answers (2)

nima
nima

Reputation: 6733

You can treat many-to-many relationships exactly like one-to-many relations in filtering:

boxes = Box.objects.filter(name__startswith='Big', pencils__title='blue')

Upvotes: 2

doniyor
doniyor

Reputation: 37934

what about this one?

boxes = Box.objects.filter(name__startswith='Big', pencils__in=[Pencil.objects.filter(color='blue')])

Upvotes: 1

Related Questions