django:链接关系对象的RelatedManager

时间:2017-11-11 12:43:41

标签: django django-orm

所以我有模特:

class Parent(models.Model):
    name = models.CharField(max_length=100)

class Child(models.Model):
    parent = models.ForeignKey('Parent', on_delete=models.CASCADE)
    name = models.CharField(max_length=100)

class Grandchild(models.Model):
    parent = models.ForeignKey('Child', on_delete=models.CASCADE)
    name = models.CharField(max_length=100)

class ParentPhoto(models.Model):
    person = models.ForeignKey('Parent', on_delete=models.CASCADE)
    image = models.ImageField()

class ChildPhoto(models.Model):
    person = models.ForeignKey('Child', on_delete=models.CASCADE)
    image = models.ImageField()

class GrandchildPhoto(models.Model):
    person = models.ForeignKey('Grandchild', on_delete=models.CASCADE)
    image = models.ImageField()

请忽略糟糕的数据库/模型设计(它只是我复杂的实际应用程序的类比)。

我想为RelatedManager名为Parent的{​​{1}}添加一个family_photo_set,该Queryset会为自己返回Photos ChildrenChildren' Grandchildren }和所有RelatedManager Parents'。我如何实现这一目标?一个简单的parentphoto_set允许我仅以某种方式过滤[fxLayout.xs]="question.isQASideBySide ? 'row' : 'column'" reloading tableview,而不是真正添加其余的家庭成员。

1 个答案:

答案 0 :(得分:1)

好的,我找到了解决办法。发布给其他访客。

class Parent(models.Model):
    name = models.CharField(max_length=100)

    def get_family_photos(self):
        family_photos = []
        family_photos.extend(self.parentphoto_set.all())

        for child in self.child_set.all():
            family_photos.extend(child.childphoto_set.all)

            for grandchild in child.grandchild_set.all()):
                family_photos.extend(grandchild.grandchildphoto_set.all())

        return family_photos

这样我可以使用它,例如在模板中

{% for photo in parent.get_family_photos %}
(...)