This is my first time building an app with django and so far I've been more than happy with it. However, I can't seem to figure out how to sufficiently optimize queries for ManyToMany relationships. Here is a model to illustrate my problem:
class Book(models.Model): name = models.CharField(max_length=255) class Reader(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) books_read = models.ManyToMany(Book, relatedName='read_by') Now I simply want to list every reader along with the books that they've read. For example: Reader Books Read ---------- ---------------------------------------------------------- Claire Smith Great Expectations Jane Eyre Wuthering Heights Dan Smith Great Expectations War and Peace Adventures of Sherlock Holmes Bob Smith Adventures of Sherlock Holmes The Call of the Wild War and Peace .... .... Ideally select_related() would work with ManyToMany relationships as well as ForeignKey relationships but I can see that this would take the model query API to a whole other level of complixity so I can understand why it hasn't been done yet. I'm used to ORM libraries like Java's Hibernate that can fetch entire graphs of objects with a minimum number of queries but I'm more than happy to do a little extra work to avoid the complexity of something like Hibernate. However, I would hope that I could fetch the necessary data to instantiate the object graph for any number of readers with only 2 queries. The queries would look like: readers = Reader.objects.filter(last_name='Smith'); books = Book.objects.filter(read_by__last_name='Smith'); These two queries get me all the data I need but I still don't have the connectivity information to know which readers have read which books. In order to get this piece of info, it looks like I'll have to drop into the native sql world and fetch the info directly from the many-to-many table created by django. Is this what necessary to do the database optimization or am I missing something? It's not so bad in this simple case but as the graph of interesting objects gets bigger, I'm afraid I may have to write a lot of this type of code. Thanks, --Dan --~--~---------~--~----~------------~-------~--~----~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---