How to check if ManyToMany field is not empty?
Asked Answered
M

2

21

How do I check if there are any ManyToMany field objects related to my model object?

For example, I have a model:

class Category(models.Model):
    related_categories = models.ManyToManyField('self', blank=True)

I want to do something only if there are related objects existing:

if example_category.related_categories:
    do_something()

I tried to do example_category.related_categories, example_category.related_categories.all(), example_category.related_categories.all().exists(), example_category.related_categories.count(), but none of these works for me.

I have no any additional conditions to filter by.

Is there any easy way to check emptiness of this field?

Mcgee answered 8/11, 2018 at 10:57 Comment(4)
What is happening if you do that, this looks like the correct solution. Note however that here your related_categories is symmetrical. So that means if a is related to b, then b is related to a.Cruz
.exists() would the right solution here.Prue
@WillemVanOnsem it looks like my condition is always true, even when there are no related objects. Can the blank argument cause this, maybe?Mcgee
@Dibidalidomba: no... blank actually has impact on the forms. But as said before, if you add a to the related_categories of b, then this means that the related_categories of a are non-empty as well.Cruz
E
31

you should use the .exists method:

related_categories = example_category.related_categories
if related_categories.exists():
    # do something
Etienne answered 8/11, 2018 at 15:11 Comment(0)
W
0

This works for me:

if hasattr(example_category, "related_categories"):
    ...
Wellfixed answered 2/8, 2024 at 21:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.