2012-01-08 100 views
3

我有以下型號複雜的Django查詢到一對多的關係

class Book(models.Model): 
    name  = models.CharField(max_length=140) 

class UserProfile(models.Model): 
    favorites = models.ManyToManyField(Book, null=True, blank=True) 
    user   = models.OneToOneField(User) 

我需要的瞭解創建的所有書籍,並顯示哪些是我的最愛,哪些不是列表。

我需要一個查詢集爲得到我所有的書像

Book.objects.all() 

,但我還需要知道每本書如果該用戶的最愛,那麼這個查詢集傳遞給模板視圖。

謝謝。

回答

2

這是ManyToManyField的相對直接的用法。

class Book(models.Model): 
    name  = models.CharField(max_length=140) 

class UserProfile(models.Model): 
    favorites = models.ManyToManyField(Book, null=True, blank=True) 
    user   = models.OneToOneField(User) 

favorite_books = this_user_profile.favorites.all() 
for b in Book.objects.all(): 
    if b in favorite_books: 
     print "Book", b.name, "is a favorite of this user!" 
    else: 
     print "Book", b.name, "is not a favorite of this user!" 

ETA:既然你說你想把它添加到模板,那麼把它作爲元組列表給它。

book_list = [(b, (b in favorite_books)) for b in Book.objects.all()] 

在你的模板,讓代碼

{% for book, is_favorite in book_list %} 
    {% if is_favorite %} 
     {% comment %} Do something with this favorite book {% endcomment %} 
    {% else %} 
     {% comment %} Do something with this non favorite book {% endcomment %} 
    {% endif %} 
{% endfor %} 
+0

感謝。也許我的問題不是很聰明,但我需要將它傳遞給印刷的模板,而這正是我遇到問題的地方。如何將這些額外的信息添加到查詢集? – manuel 2012-01-08 20:59:32

+0

這是完美的。謝謝! – manuel 2012-01-08 21:04:58