Django 如何查询模型中未指定的ForeignKeyField对象
我有以下模型&假设我们有5个Django 如何查询模型中未指定的ForeignKeyField对象,django,django-models,django-forms,django-templates,Django,Django Models,Django Forms,Django Templates,我有以下模型&假设我们有5个SouceCode对象和2个Project对象 在5个SouceCode对象中我将源代码的2个对象作为ForiegnKeyField添加到项目模型中。 现在,如何打印/查询未用作项目模型的ForeignKeyField的3个SourceCode对象。 型号.py class SourceCode(models.Model): source_description = models.CharField(max_length=80,unique=True)
SouceCode
对象和2个Project
对象
在5个SouceCode对象中
我将源代码的2个对象作为ForiegnKeyField添加到项目模型中。
现在,如何打印/查询未用作项目模型的ForeignKeyField的3个SourceCode对象。
型号.py
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
models的所有未分配对象,并打印该对象的source\u说明
谢谢。您应该做的是获取所有源代码
对象的ID,然后从该列表中减去分配给源代码
的所有项目
对象。比如,
# 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)
也许我误解了这个问题,但似乎您想要的只是SourceCode
对象,这些对象的项目
模型具有空的反向ForeignKey集:
descriptions = SourceCode.objects.filter(
project__isnull=True
).values_list('source_description', flat=True)
这里,filter
会删除至少连接到一个项目的任何SourceCode
对象,而values\u list
调用会拉出所需的字段。unassigned\u id=set(source\u id-linked\u source\id)类型错误:不支持的操作数类型对于-:“QuerySet”和“QuerySet”
@arbazzhussa强制它们成为列表<代码>设置(列表(源ID)-列表(链接的源ID))