你需要像下面那样改变你的模型。我们应该用“亲子关系”来实现你的目标。
class Category(models.Model):
CATEGORIES = (
('ACT', 'Action'),
('THRILLER', 'Thriller'),
('COM', 'Comedy'),
('WEST', 'Western'),
('MILITARY', 'Military'),
)
image = models.ImageField()
description = models.CharField(max_length=500)
quantity = models.IntegerField()
category = models.CharField(
max_length=10,
choices=CATEGORIES
)
date_posted = models.DateTimeField(auto_now_add=True, blank=True)
parent = models.ForeignKey('self', null=True, blank=True, related_name="childs")
访问父级和子级的示例:
parents = Category.objects.filter(parent=None)
parent = parents[0] # create some categories before using it
childs = parent.childs.all()