bs = BookSequence.objects.filter(book__pk=1).select_related() for s in bs: print s.sequence.name, s.number_in_sequence
On Sun, May 1, 2011 at 1:30 PM, Alex <4d876...@gmail.com> wrote: > Hello! > Assume we have the following models: > > > class Book(models.Model): > title = models.CharField() > sequences = models.ManyToManyField(Sequence, > through='BookSequence') > > class Sequence(models.Model): > name = models.CharField(unique=True) > > class BookSequence(models.Model): > class Meta: > unique_together = ('book', 'sequence') > > book = models.ForeignKey(Book) > sequence = models.ForeignKey(Sequence, related_name='detail') > number_in_sequence = models.IntegerField() > > > ...and are trying to select the sequences a concrete book belongs to, > along with the number of this book in the sequence: > > > def print_book_sequences(): > book = Book.objects.get(pk=1) > for seq in book.sequences.select_related(): > number_in_sequence = seq.detail.get(book=book, > sequence=seq).seq_number > print seq.name, number_in_sequence > > > So, the question is: > > Is there any way in django to select sequence name and sequence number > in one sql query? > The code in print_book_sequences results in two sql queries per > sequence, one selecting name and one number. > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.