【问题标题】:Django: check if ManyToManyField is empty from a Field objectDjango:检查 Field 对象中的 ManyToManyField 是否为空
【发布时间】: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 referenceManyToManyField reference 中未找到相关选项

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    getattr(school,field.name).exists() 为我工作。但是所有人都知道是否有更好的方法

    (即查询 model_object.field 而不是字段对象)

    【讨论】:

      【解决方案2】:

      在我的例子中,我覆盖了模型的 clean() 方法,如果 m2m 字段为空,则必须执行验证。 getattr() 返回了一个异常,所以我不得不使用 .count()。这也应该适用于 django-modelcluster 的 ParentalManyToMany 字段。

      def clean(self, *args, **kwargs):  
          if self.m2m_field.count() == 0: 
                  raise ValidationError("No children")
      

      【讨论】:

      • 这种方式会导致服务器错误,因为对象还没有保存,所以它没有ID,然后我们不能为一个对象调用self.m2m_field.*未保存。
      【解决方案3】:

      改用first() 怎么样?这绝对应该比all() 运行得更快,并且可能比count() 运行得更快。

      IE:

      def __str__(self):
          if self.m2mField.first():
              print('Object where m2mField contains stuff.')
          else:
              print('Object with nothing in m2mField.')
      

      【讨论】:

        最近更新 更多