首页 > 解决方案 > 如何检查 ManyToMany 字段是否为空?

问题描述

如何检查是否有与我的模型对象相关的 ManyToMany 字段对象?

例如,我有一个模型:

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

我只想在存在相关对象的情况下做某事:

if example_category.related_categories:
    do_something()

我试着做example_category.related_categories, example_category.related_categories.all(), example_category.related_categories.all().exists(), example_category.related_categories.count(),但这些都不适合我。

我没有任何其他条件可供过滤。

有没有简单的方法来检查这个字段的空虚?

标签: pythondjangodjango-models

解决方案


你应该使用 .exists 方法:

related_categories = example_category.related_categories
if related_categories.exists():
    # do something

推荐阅读