如何在 Django 模板中遍历反向泛型关系?

发布于 2024-10-10 19:41:48 字数 797 浏览 4 评论 0原文

我有以下类,用于为项目添加书签:

class BookmarkedItem(models.Model):
     is_bookmarked = models.BooleanField(default=False)
     user = models.ForeignKey(User)
     content_type = models.ForeignKey(ContentType)
     object_id = models.PositiveIntegerField()
     content_object = generic.GenericForeignKey()

并且我正在定义反向通用关系,如下所示:

class Link(models.Model):
    url = models.URLField()
    bookmarks = generic.GenericRelation(BookmarkedItem)

在我的一个视图中,我生成所有链接的查询集并将其添加到上下文中:

links = Link.objects.all()
context = {
     'links': links
}
return render_to_response('links.html', context)

我遇到的问题是如何遍历我的模板中的通用关系。对于每个链接,我希望能够检查 is_bookmarked 属性,并根据用户是否已将其添加为书签来更改添加/删除书签按钮。这可以在模板中完成吗?或者我是否必须在视图中进行一些额外的过滤并传递另一个查询集?

I have the following class that I am using to bookmark items:

class BookmarkedItem(models.Model):
     is_bookmarked = models.BooleanField(default=False)
     user = models.ForeignKey(User)
     content_type = models.ForeignKey(ContentType)
     object_id = models.PositiveIntegerField()
     content_object = generic.GenericForeignKey()

And I am defining a reverse generic relationship as follows:

class Link(models.Model):
    url = models.URLField()
    bookmarks = generic.GenericRelation(BookmarkedItem)

In one of my views I generate a queryset of all links and add this to a context:

links = Link.objects.all()
context = {
     'links': links
}
return render_to_response('links.html', context)

The problem I am having is how to traverse the generic relationship in my template. For each link I want to be able to check the is_bookmarked attribute and change the add/remove bookmark button according to whether the user already has it bookmarked or not. Is this possible to do in the template? Or do I have to do some additional filtering in the view and pass another queryset?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

揽清风入怀 2024-10-17 19:41:48

由于您已经定义了“书签”GenericRelation 字段,因此您可以迭代它:

{% for bookmark in link.bookmarks.all %}

Since you have defined the 'bookmarks' GenericRelation field, you can just iterate through that:

{% for bookmark in link.bookmarks.all %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文