开发者

Correct way to model recursive relationship in Django

开发者 https://www.devze.com 2022-12-23 19:40 出处:网络
My application has two node types: a parent node which can hold recursive child nodes. Think of it like the post-comment system in SO, but comments can be recursive:

My application has two node types: a parent node which can hold recursive child nodes. Think of it like the post-comment system in SO, but comments can be recursive:

parent_1
  child_11
  child_12
    child_121
  child_13
parent_2
  child_21
    child_211
      child_2111

Important to note that the parent nodes have different attributes and behavior than the child nodes.

Barring recursion I would have the following models:

class Parent(models.Model):
    # fields ...

class Child(models.Model):
    parent = models.ForeignKey(Parent)
    # other fields ...

But the recursion complicates this. What is the开发者_运维百科 correct (and presumably most efficient) way of modeling this relationship in Django?


With django-mptt or django-treebeard.


Could you use a Generic Relation and just add validation in the save() method (or in a signal or form validation) to ensure the object is an instance of one or the other?

0

精彩评论

暂无评论...
验证码 换一张
取 消