代码之家  ›  专栏  ›  技术社区  ›  Arbazz Hussain

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

  •  0
  • Arbazz Hussain  · 技术社区  · 6 年前

    我有以下型号,假设我们有5台 SouceCode 对象&2 Project 物体。

    由于 5 SouceCode objects 我补充说 2 objects 源代码为的 ForiegnKeyField to Project Model.

    现在,如何打印/查询 3 SourceCode objects 它还没有被用作 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 模型和打印 source_description 那个物体的

    谢谢。

    2 回复  |  直到 6 年前
        1
  •  1
  •   markwalker_    6 年前

    也许我误解了这个问题,但你想要的只是 SourceCode 将反向ForeignKey设置为空的对象 Project 模型:

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

    这里 filter 杂草丛生 源代码 对象连接到至少一个项目,并且 values_list 呼叫会拉出您想要的字段。

        2
  •  0
  •   markwalker_    6 年前

    你应该做的是得到所有 SourceCode 对象,然后从该列表中减去所有 Project 分配给的对象 源代码 . 例如;

    # 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)