【问题标题】:Complex django query in a many to many relationship多对多关系中的复杂 django 查询
【发布时间】:2012-01-08 20:48:59
【问题描述】:

我有以下型号

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()

但我还需要知道每本书是否是该用户的最爱,然后将此查询集传递给模板。

谢谢。

【问题讨论】:

    标签: python django django-models django-queryset


    【解决方案1】:

    这是 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 %}
    

    【讨论】:

    • 谢谢。也许我的问题不是很明确,但我需要将它传递给打印模板,这就是我遇到的问题。如何将此额外信息添加到查询集中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    相关资源
    最近更新 更多