如何在模型中查询未分配的ForeignKeyField对象

时间:2018-12-19 23:15:00

标签: django django-models django-forms django-templates

我有以下模型,并假设我们有5个SouceCode对象和2个Project对象。

5 SouceCode objects中,我已将2 objects的SourceCode添加为ForiegnKeyField to Project Model.

现在,如何打印/查询尚未用作3 SourceCode objects的{​​{1}}


models.py

ForeignKeyField for Project Model.

我知道的一种可能的方法是:

class SourceCode(models.Model):
    source_description = models.CharField(max_length=80,unique=True)
    source_urls = ArrayField(ArrayField(models.TextField(blank=True),),blank=True,null=True,default=list)
    source_results = JSONField(blank=True,null=True,default=dict)


class Project(models.Model):
    project_name = models.CharField(max_length=200,unique=True)
    project_sourcecode_O2M = models.ForeignKey(SourceCode,on_delete=models.SET_NULL,blank=True, null=True)

我正在为此寻找一个很好的替代解决方案。

我想过滤project_source_code_list = [] for each_project in Project.objects.all(): project_source_code_list.append(each_project.project_sourcecode_O2M.source_description) for each_source_code in SourceCode.objects.all(): source_description = each_source_project.source_description if source_description not in project_source_code_list: print("YEP Not there") 模型的所有未分配对象并打印该对象的SourceCode

谢谢。

2 个答案:

答案 0 :(得分:1)

也许我在误解这个问题,但是似乎您想要的只是SourceCode个对象,这些对象的Project模型具有空的反向ForeignKey集:

descriptions = SourceCode.objects.filter(
    project__isnull=True
).values_list('source_description', flat=True)

这里filter清除了连接到至少一个项目的任何SourceCode对象,并且values_list调用提取了您想要的字段。

答案 1 :(得分:0)

您应该做的是获取所有SourceCode对象的ID,然后从该列表中减去分配给Project的所有SourceCode对象。例如;

# get the IDs of all SourceCode objects
source_ids = SourceCode.objects.values_list('id', flat=True)

# get the IDs of the SourceCode objects attached to a Project
linked_source_ids = Project.objects.values_list('project_sourcecode_O2M_id', flat=True)

# get the difference leaving the SourceCode IDs not linked to a Project
unassigned_ids = set(source_ids - linked_source_ids)

# get the SourceCode objects
unassigned_sourcecode = SourceCode.objects.filter(id__in=unassigned_ids)