Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Filter Query Foreign Key

Tags:

django

I'm struggling getting the right query for my project. Here is an example or my model :

from django.db import models  class Publisher(models.Model):     name = models.CharField(max_length=30)     address = models.CharField(max_length=50)     city = models.CharField(max_length=60)     state_province = models.CharField(max_length=30)     country = models.CharField(max_length=50)     website = models.URLField()      def __unicode__(self):         return self.name  class Author(models.Model):     first_name = models.CharField(max_length=30)     last_name = models.CharField(max_length=40)     email = models.EmailField()      def __unicode__(self):         return u'%s %s' % (self.first_name, self.last_name)  class Book(models.Model):     title = models.CharField(max_length=100)     authors = models.ManyToManyField(Author)     publisher = models.ForeignKey(Publisher)     publication_date = models.DateField()      def __unicode__(self):         return self.title 

how do I get publisher from the book class for example I want to get all publisher for all books that have the title starting with 'hello'?

like image 803
flo bee Avatar asked Mar 19 '13 18:03

flo bee


1 Answers

If you want to get Publishers, you have to start with Publisher. That means you have to query through the Book → Publisher relation backwards. Here's what the docs say about it:

Lookups that span relationships

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

...

To refer to a “reverse” relationship, just use the lowercase name of the model.

The query:

Publisher.objects.filter(book__title__startswith='hello') 
like image 81
Pavel Anossov Avatar answered Sep 19 '22 01:09

Pavel Anossov