Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
smbatpetrosyan Avatar asked Jul 01 '12 05:07

smbatpetrosyan


1 Answers

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

Queries over related objects

like image 171
notbad.jpeg Avatar answered Sep 22 '22 15:09

notbad.jpeg