Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Children of an Object With ForeignKey in Django?

Tags:

python

django

I'm brand new to Django, so the answer to this is probably very simple. However, I can't figure it out.

Say I have two bare-bones Models.

class Blog(models.Model):
    title = models.CharField(max_length=160)
    text = models.TextField()

class Comment(models.Model):
    blog = models.ForeignKey(Blog)
    text = models.TextField()

In the Python/Django shell, if I have a Blog object in a variable (say blog = Blog.objects.get(id=3)), how do I select all its child comments?

This doesn't seem to work: blog.objects.all()

like image 263
Vortico Avatar asked Aug 20 '10 23:08

Vortico


1 Answers

to follow foreign keys 'backwards' you use

blog.comment_set.all()
like image 51
second Avatar answered Nov 15 '22 14:11

second