How to do a reverse foreignkey lookup for all records in Django?
I'm trying to do a reversed SQL lookup using Django 1.3. I found a lot of related questions, but unfortunately I can only find the answer for doing this on a single record, not on multiple records at once.
Basically, this is my case: I have a model 'Techniques' which looks like this:
class Technique(models.Model):
title = models.CharField(max_length=32)
description = models.CharField(max_length=256)
skill_level = models.IntegerField()
parent_technique = models.ForeignKey('self', blank=True, null=True)
At the moment I just make a list of all the parentless techniques.
t = get_list_or_404(Technique.objects.filter(parent_technique=None))
Now what I want (or at least think I want) is that all the entries in t
get an addition field 'childs' that lists all the techniques that list the current technique as their parent. Can anyone help me with this?
Also, if their is another way to achieve what I want, please feel free to contribute it. I've jus开发者_StackOverflow中文版t begun using Django so I might not know about any alternate ways.
Thanks a lot in advance!
This is built-in already - see following relations backwards.
In your case, just do:
obj.technique_set.all()
for each obj
in t
.
in model add related_name
parent_technique = models.ForeignKey('self', blank=True, null=True, related_name="childrens_tech")
all children techniques of smt_technique are
smt_technique.childrens_tech.all()
精彩评论