我是这样看的...
您的模型看起来很接近,m2m 似乎合适,但您的图表看起来更像:
Item1
---> TopLevel1 (accessed through `categories`)
---> SubLevel1 (accessed through `Category.children`, see below)
---> SubLevel2 (accessed through `Category.children`, see below)
你的模型看起来更像
class Category(models.Model):
name = models.CharField(max_length=128) # `blank` is false by default
parent = models.ForeignKey('self', null=True, blank=True, related_name='children') # by giving this field a nice `related_name`, we can easily access the linked categories
class Item(TimeStampedModel):
name = models.TextField() # `null` and `blank` are false by default
categories = models.ManyToManyField(Category, null=True, blank=True, related_name='items')
现在,如果您有一个项目并且想获得它的顶级类别,您可以循环item.categories.all()
{% for category in item.categories.all %}
Top Level: {{ category.name }}
{% endfor %}
并访问子级别类别,您循环遍历children.all()
每个category
{% for category in item.categories.all %}
Top Level: {{ category.name }}
{% for child in category.children.all %}
Sub Level: {{ child.name }}
Parent: {{ child.parent.name }}
{% endfor %}
{% endfor %}
您还可以获得一个类别中的所有项目
{% for item in category.items.all %}
Item: {{ item.name }}
{% endfor %}
或者如果您属于顶级类别
{% for child in category.children.all %}
{{ child.name }}
{% for item in child.items.all %}
Item: {{ item.name }}
{% endfor %}
{% endfor %}
与
category_one = Category.objects.create('category one')
category_two = Category.objects.create('category two')
item_one = Item.objects.create('item one')
您可以通过相关管理器添加一个Category
categories
Item
item_one.categories.add(category_one, category_two)
或者您可以通过相关经理添加Item
items
Category
category_one.items.add(item_one)