Django:检查一个Field对象中的ManyToManyField是否为空

时间:2017-05-11 05:03:47

标签: django django-models django-views

这看起来非常简单,但令人惊讶的是还没有找到关于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帖子看起来很相似,但是要过滤所有在Model对象中为空的ManyToManyFields,所以对上述情况没有帮助。

all()count()empty()exists()似乎不适用于ManyToManyFields。

if (field):返回True(因为它指的是经理)

未在Field referenceManyToManyField reference

中找到相关选项

3 个答案:

答案 0 :(得分:1)

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

(即查询model_object.field而不是field object)

答案 1 :(得分:0)

就我而言,我正在为模型重写clean()方法,并且如果m2m字段为空,则必须执行验证。 getattr()返回了一个异常,因此我不得不使用.count()。这也应适用于django-modelcluster的ParentalManyToMany字段。

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

答案 2 :(得分:0)

改为使用 I use some scripts under script section: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="~/js/bootstrap.min.js"></script> 怎么样?绝对应该比first()快,并且可能比all()快。

IE:

count()