Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: None  |  size: 1.13 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Django using the values method with m2m relationships / filtering m2m tables using django
  2. class Book(models.Model):
  3.     name = models.CharField(max_length=127, blank=False)
  4.  
  5. class Author(models.Model):
  6.     name = models.CharField(max_length=127, blank=False)
  7.     books = models.ManyToMany(Books)
  8.        
  9. [{id: 1, name: 'Grisham', books : [{name: 'The Client'},{name: 'The Street Lawyer}], ..]
  10.        
  11. Author.objects.all().values('name', 'books')
  12.        
  13. [{id: 1, name: 'Grisham', books :{name: 'The Client'}},{id: 1, name: 'Grisham', books :{name: 'The Street Lawyer'}}]
  14.        
  15. authors = Authors.objects.all().values('id')
  16. q = Q()
  17. for id in authors:
  18.    q = q | Q(author__id = id)
  19.  
  20. #m2m author book table.. from my understanding it is
  21. #not accessible in the django QuerySet
  22. author_author_books.filter(q)  #grab all of the book ids and author ids with one query
  23.        
  24. authors = Author.objects.prefetch_related('books').all()
  25.        
  26. class BookAuthor(models.Model):
  27.   book = models.ForeignKey(Book)
  28.   author = models.ForeignKey(Author)
  29.  
  30. class Author(models.Model):
  31.   name = models.CharField(max_length=127, blank=False)
  32.   books = models.ManyToMany(Books, through=BookAuthor)