【发布时间】:2024-05-22 05:45:02
【问题描述】:
这看起来超级简单,但令人惊讶的是在 SO 或 Django 文档上找不到任何线索。
我想检查一个特定的 ManyToManyField 是否为空,但还想不出办法。如果有帮助,这是我的确切用例:
for field in school._meta.get_fields(): # school is the Model object
if (field.get_internal_type() == 'ManyToManyField'):
#if (find somehow if this m2m field is empty)
#do something if empty
else:
if (field.value_to_string(self) and field.value_to_string(self)!='None'):
#do something when other fields are blank or null
发现this 帖子看起来很相似,但它是关于过滤模型对象中所有为空的ManyToManyFields,因此对上述情况没有帮助。
all() 或 count() 或 empty() 或 exists() 似乎不适用于多对多字段。
if (field): 返回True(因为它指的是经理)
在Field reference 或ManyToManyField reference 中未找到相关选项
【问题讨论】:
标签: django django-models django-views