Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an item is in another item's ManyToMany field?

Tags:

django

In Django, I am interested in checking if an item is in another item's ManyToMany field. How can I do that?

like image 235
nubela Avatar asked Jun 06 '09 20:06

nubela


1 Answers

Set the related_name attribute.

If object Egg has a ManyToManyField pointing to Spam, and you set the related name to egg_set, you can access the eggs via Spam.egg_set.all() (or use filter() to get a specific egg as shown below).

So to check if the Spam object my_spam has the Egg with the ID 42, you could do something like:

if my_spam.egg_set.filter(pk=42):
    fry_bacon()
like image 192
mikl Avatar answered Oct 18 '22 13:10

mikl