Django, topic model with subtopics
i wanted to create a topic model. this model would have a foreign key, non required, to 开发者_C百科the topic above it for example:
iphone has a foreign key to apple
but what do i do if i want apple to be linked to all of its sub elements
apple to iPhone apple to mac
i know that there are many to many fields, but how exactly would you apply them to this situation
furthermore mac or iPhone might even have more sub elements
You probably want to look at the documentation for related_name
. Basically Django does this for you. For example:
class Topic(models.Model):
master_topic = models.ForeignKey('self',
null=True,
blank=True,
related_name="sub_topics")
Then access this code:
apple = Topic.objects.filter(tag='Apple')
sub_topics = apple.sub_topics.all() ## Gets all sub_topics.
精彩评论