views:

528

answers:

2
class Achievement(MyBaseModel):
    parent_achievement = models.ForeignKey('self', blank=True, null=True, help_text="An achievement that must be done before this one is achieved") # long name since parent is reserved

I can do :

Achievement.objects.get(pk="1").parent_achievement

which is great. But how do I get all the children?

Achievement.objects.get(pk="1").parent_achievement_set

doesn't work (and probably should have some more notation around it), and I didn't see too much when searching.

Is it possible? Fall into SQL?

+4  A: 

By default, django will call the reverse the model name, followed by "_set", so it would be

Achievement.objects.get(pk="1").achievement_set

If that doesn't suit you, use the related_name optional argument to models.ForeignKey:

class Achievement(MyBaseModel):
    parent_achievement = models.ForeignKey(
        'self', 
        blank=True, 
        null=True, 
        help_text="An achievement that must be done before this one is achieved",
        related_name="child_achievement_set"
    ) # long name since parent is reserved

Achievement.objects.get(pk="1").child_achievement_set
TokenMacGuy
wonderful. worked great. would buy again. A++
Paul Tarjan
A: 

Don't know if this is the best way, but this also gets the job done

Achievement.objects.filter(parent_achievement=1)

or

Achievement.objects.filter(parent_achievement__pk=1)
sajal