smbatpetrosyan
smbatpetrosyan

Reputation: 659

django - Filter foreign key against object

class Blog(models.Model):
    name = models.CharField(max_length=100)

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)

Is the following query correct?

a = Blog.objects.get(id__exact=14)
b = Entry.objects.filter(blog = a)

I comprehend that that any of the following methods are more elegant and even recommended.

Entry.objects.filter(blog__id__exact=3) # Explicit form
Entry.objects.filter(blog__id=3)        # __exact is implied
Entry.objects.filter(blog__pk=3)        # __pk implies __id__exact

In other words, can I pass an object (model instance) as an argument value?

Please also provide some guidance on where can find explicit documentation on this?

Upvotes: 6

Views: 4223

Answers (2)

notbad.jpeg
notbad.jpeg

Reputation: 3368

Yes, according to the django docs; you can use the instance of a row to do a filter.

Queries over related objects

Upvotes: 4

Daniel Roseman
Daniel Roseman

Reputation: 600059

Alternative:

a = Blog.objects.get(pk=3)
b = a.blog_set.all()

Upvotes: 1

Related Questions