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'?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With