In Django, I am interested in checking if an item is in another item's ManyToMany field. How can I do that?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With