复杂的Django查询到一对多的关系
问题描述:
我有以下型号复杂的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()
,但我还需要知道每本书如果该用户的最爱,那么这个查询集传递给模板视图。
谢谢。
答
这是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 %}
感谢。也许我的问题不是很聪明,但我需要将它传递给印刷的模板,而这正是我遇到问题的地方。如何将这些额外的信息添加到查询集? – manuel 2012-01-08 20:59:32
这是完美的。谢谢! – manuel 2012-01-08 21:04:58