Django 过滤空字段

Django filter empty fields

目前我正在过滤查询集所有条目中的空字段,如下所示:

data_qs = DataValue.objects.filter(study_id=study.id) #queryset

opts = DataValue._meta  # get meta info from DataValue model
   
field_names = list([field.name for field in opts.fields])  # DataValue fields in a list

field_not_empty = list() # list of empty fields

for field in field_names:
    for entry in data_qs.values(field):
        if entry.get(field) is not None:
            field_not_empty.append(field)
            break

它有效,但不确定它是否是合适的解决方案....

有谁知道如何过滤所有查询集中的空值? table 有超过 30 个字段,因此根据研究 ID,一些查询集可能包含 field1 全空,其他研究 ID 可能包含所有 field2 空。

Django ORM 是否提供简单干净的解决方案来执行此操作?

提前致谢

要检查 QuerySet 中的某个值是否为空,假设值名称是“title”。

这将排除所有空字段

DataValue.objects.filter(study_id=study.id).exclude(title__exact='')

如果您只想要空字段,只需过滤它

DataValue.objects.filter(study_id=study.id, title__exact='')

希望对您有所帮助。