Vortico
Vortico

Reputation: 2749

Select Children of an Object With ForeignKey in 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()

Upvotes: 19

Views: 25473

Answers (1)

second
second

Reputation: 28637

to follow foreign keys 'backwards' you use

blog.comment_set.all()

Upvotes: 48

Related Questions