如何检查ManyToMany字段是否不为空?

2024-04-30

如何检查是否有与我的模型对象相关的 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(),但这些都不适合我。

我没有任何额外的条件可以过滤。

有没有简单的方法来检查该字段是否为空?


你应该使用 .exists 方法:

related_categories = example_category.related_categories
if related_categories.exists():
    # do something
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查ManyToMany字段是否不为空? 的相关文章

随机推荐