NicoleZ
NicoleZ

Reputation: 1780

Filter model using many to many field as criteria Django

I want to get all objects that contain the certain many to many field id.i go through a whole lot of SO Post I didn't get it at all. my question is

class Pizza(models.Model):
 name = models.CharField(max_length=30)
 toppings = models.ManyToManyField('Topping')

def __str__(self):
    return self.name


class Topping(models.Model):
  tp_id = AutoField(primary_key=True)
  name = models.CharField(max_length=30)

  def __str__(self):
     return self.name

i want to get all pizzas objects which has tp_id = x.i tried something like this in view

 filterdObjects =  Pizza.objects.filter(toppings = 1)

Upvotes: 0

Views: 79

Answers (1)

Erfan
Erfan

Reputation: 379

first you have to filter all Topping objects some how you expect.for example:

    all_toppings = Topping.objects.filter(tp_id=1)

use filter,even you know that there is just one match because of filtering by the unique field(id). and then you should get your Pizza objects filtered with:

    target_pizza = Pizza.objects.filter(topping__in = all_toppings)

for filtering by many to many relations you must check the many_to_many filed with a list of objects from target model and for default model managers in django, filter method will return the list data type containing filtered objects.

Upvotes: 2

Related Questions