python - 如何检查 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()
,但这些都不适合我。
我没有任何其他条件可供过滤。
有没有简单的方法来检查这个字段的空虚?
解决方案
你应该使用 .exists 方法:
related_categories = example_category.related_categories
if related_categories.exists():
# do something
推荐阅读
- powerbi - 计算两年之间金额的差异(差异)
- python - Bonobo ETL:如何在执行期间为所有节点提供全局上下文?
- c# - 如何解析div,因为我想要h3标签内的超链接
- javascript - net::ERR_CONNECTION_REFUSED 使用 websockets
- mysql - 通过连接两个表,总和的结果是重复的
- ios - 如何获取表格视图中可见行内容背后的键?
- python - 使用beautifulsoup python在h3和p标签中抓取文本
- typescript - 使用模型类创建条目
- julia - Julia 中的 PlotlyJS:xaxis 设置
- javascript - 使用此特定代码使用 JavaScript 在实际网页上打印一些消息的最简单方法