TIMEX
TIMEX

Reputation: 271614

How would I make this query in Django?

class Content(models.Model):
    author = models.ForeignKey('auth.User')
    stamp = models.CharField(max_length=50)

class Comments(models.Model):
    content = models.ForeignKey(Content)
    message = models.TextField()

I want to get all the comments for content that the current logged in user created. But this doesn't work:

Comments.objects.filter(content.author = request.user)

Upvotes: 0

Views: 91

Answers (1)

miku
miku

Reputation: 188004

Use field lookups:

Comments.objects.filter(content__author=request.user)

Django offers a powerful and intuitive way to "follow" relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.

Upvotes: 6

Related Questions