首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何查询模型中未赋值的ForeignKeyField对象

如何查询模型中未赋值的ForeignKeyField对象
EN

Stack Overflow用户
提问于 2018-12-20 07:15:00
回答 2查看 26关注 0票数 0

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

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

现在,如何打印/查询未用作ForeignKeyField for Project Model.3 SourceCode objects

models.py

代码语言:javascript
复制
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)

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

代码语言:javascript
复制
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模型的所有未分配对象并打印这些对象的source_description

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-20 07:37:28

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

代码语言:javascript
复制
descriptions = SourceCode.objects.filter(
    project__isnull=True
).values_list('source_description', flat=True)

在这里,filter将剔除任何连接到至少一个项目的SourceCode对象,而values_list调用将剔除您想要的字段。

票数 1
EN

Stack Overflow用户

发布于 2018-12-20 07:28:18

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

代码语言:javascript
复制
# 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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53860469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档