Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if ManyToMany field is not empty?

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?

like image 747
Dibidalidomba Avatar asked Nov 08 '18 10:11

Dibidalidomba


1 Answers

you should use the .exists method:

related_categories = example_category.related_categories
if related_categories.exists():
    # do something
like image 113
Karina Kozarova Avatar answered Nov 13 '22 04:11

Karina Kozarova