如何在Django中获取互连记录?

2024-10-03 11:16:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个django模型,叫做Person和PersonRelation

class Person(model.Models):
     person_name = models.charfield(max_length=255, blank=False)
     person_address = models.charfield(max_length=255, blank = False)

class PersonRelation(model.Models):
     person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='sibling_of')
     person_relation = models.ForeignKey(Person, on_delete=models.CASCADE)

现在让我们说:

SAM is Related to JOHN
SMITH is Related to JOHN
TOM is related to SMITH

如何从数据库中获取所有相关的兄弟姐妹

相关兄弟姐妹的所需输出: 山姆-约翰-史密斯-汤姆

enter image description here

enter image description here


Tags: tonamefalsemodelismodelslengthmax
1条回答
网友
1楼 · 发布于 2024-10-03 11:16:55

所以我使用递归:)

from relations.models import Person, PersonRelation
from django.shortcuts import get_object_or_404

sibling_list = {"id_list":[], "sib_list":[]}

def related(person):

    direct_relation = PersonRelation.objects.filter(person__id = person.id)

    if direct_relation:
        for drel in direct_relation:
            if drel.person_relation.id not in sibling_list["id_list"]:
                sibling_list["id_list"].append(drel.person_relation.id)
                sibling_list["sib_list"].append(drel.person_relation)
            
            related(drel.person_relation)
        
    indirect_relation(person)

def indirect_relation(person):

    indirect_relation = PersonRelation.objects.filter(person_relation=person)

    if indirect_relation:
        for inrel in indirect_relation:
            if inrel.person.id not in sibling_list["id_list"]:
                sibling_list["id_list"].append(inrel.person.id)
                sibling_list["sib_list"].append(inrel.person)
                related(inrel.person)

    
def get_siblings(person_id):
    global sibling_list
    person = get_object_or_404(Person, pk=person_id)
    related(person)
    sib_list = list(sibling_list["sib_list"])
    sibling_list = {"id_list":[], "sib_list":[]}

    return sib_list

相关问题 更多 >