Sunday, May 1, 2011

fetching data from intermediate many-to-many table

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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment