django 祖父母父子关系

时间:2021-04-20 21:12:50

标签: python django django-rest-framework

我有以下模型的 Django 休息框架

class Grandparent(models.Model):
    grandparent_name = CharField(max_length=20)
    grandparent_address = CharField(max_length=20)
    grandparent_phone = CharField(max_length=20)

class Parent(models.Model):
    grandparent = ForeignKey(Grandparent)
    parent_name = CharField(max_length=20)
    parent_address = CharField(max_length=20)
    parent_phone = CharField(max_length=20)

class Child(models.Model):
    parent = ForeignKey(Parent)
    grandparent = ForeignKey(Grandparent)
    child_name = CharField(max_length=20)

所有 3 个模型都在 admin.py 中注册。从 django 管理站点向子模型添加条目时,父和祖父的下拉列表是独立的。换句话说,我可以选择一个祖父母和父母,它们不像“父”表中那样绑定。

这是我想要实现的目标: 选择祖父母后,父字段应仅显示一个下拉列表,其中包含每个“父”模型选择的祖父母。

我怎样才能做到这一点?

已编辑:向祖父母和父类添加了地址/电话字段。

1 个答案:

答案 0 :(得分:0)

如果您想看看单节点模型是什么样子,我已经为您构建了一个小模型。

from django.db import models
from django.core.exceptions import ValidationError

class FamilyMember(models.Model):
    name = models.CharField(max_length=20)
    phone = models.CharField(max_length=20, blank=True, null=True)
    address = models.CharField(max_length=50, blank=True, null=True)

    # The mother and father are necessary for a children to exist. 
    # Therefore, the children can always be linked with a father and a mother, which 
    # also happens to have a mother and a father, and it goes on and on. (The last children would have blank field)
    # A father or a mother could be ommitted and everything would work just fine.
    mother = models.ForeignKey('self', related_name='familymember_mother', blank=True, null=True, on_delete=models.SET_NULL)
    father = models.ForeignKey('self', related_name='familymember_father', blank=True, null=True, on_delete=models.SET_NULL)

    def get_children(self):
        """
        Returns the direct children of this node.
        If there are none, it returns an empty list.
        """
        children_mother_side = list(FamilyMember.objects.filter(mother=self))
        print(children_mother_side)
        children_father_side = list(FamilyMember.objects.filter(father=self))
        return children_mother_side + children_father_side

    def get_grandparents(self):
        """
        Returns the grandparents of this node as a list.
        If there are none, it returns an empty list.
        """
        grand_parents = []
        if self.mother is not None:
            if self.mother.mother is not None:
                grand_parents.append(self.mother.mother)
            if self.mother.father is not None:
                grand_parents.append(self.mother.father)
        if self.father is not None:
            if self.father.mother is not None:
                grand_parents.append(self.father.mother)
            if self.father.father is not None:
                grand_parents.append(self.father.father)
        return grand_parents

    def save(self, *args, **kwargs):
        if self.mother == self or self.father == self or (self.mother == self.father and self.mother is not None):
            raise ValidationError('You can\'t have yourself as a parent!')
        return super(FamilyMember, self).save(*args, **kwargs)
    
    def __str__(self):
        return self.name


这个模型有收集祖父母和孩子的方法(父母显然也可以访问)。

这只是它可能的样子的一个例子。

从这里,您可以在 doc 的帮助下按照最初的意愿编辑管理页面表单。

这门课并不完美,但应该能让你入门!