如何在 Django 模板中遍历反向泛型关系?
我有以下类,用于为项目添加书签:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您已经定义了“书签”GenericRelation 字段,因此您可以迭代它:
Since you have defined the 'bookmarks' GenericRelation field, you can just iterate through that: