在django-tables2中显示多对多相关记录 [英] Display relevant records from many to many in django-tables2
问题描述
好的,所以我有一个Item类,它通过'Roles'类具有User的多对多属性.我正在尝试为Items创建一个django表,以便在附加到该项目的任何角色中,如果当前用户已附加到该角色,则显示该角色的名称.我希望这是有道理的.到目前为止,这是我真正没有想到的工作,因为我看不到Table类如何知道请求/用户.我被卡住了.
OK, so I have an Item class that has a many-to-many attribute to User through a 'Roles' class. I am trying to create a django-table for the Items such that out of any of the roles attached to the item, if the current User is attached to that role, the name of the role displays. I hope that makes some sort of sense. Here's what I have so far, which I didn't really expect to work because I don't see how the Table class can know about the request/user. I'm stuck.
models.py
models.py
class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User, related_name='Owner')
roles = models.ManyToManyField(User, through='Role')
class Role(models.Model):
role_type = models.ForeignKey(RoleType)
user = models.ForeignKey(User)
item = models.ForeignKey(Item)
tables.py
tables.py
class OwnedTable(tables.Table):
roles = tables.Column()
user = request.user
def render_roles(self):
for role in roles:
if role.User == user:
return role.role_type
else:
pass
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ('id', 'name', 'owner', 'roles')
推荐答案
您可以从 self.context
获取 request
对象.因此,如果您只需要 request.user
,那是做到这一点的一种方法.
You can get the request
object from self.context
. So if you only need request.user
, that's one way to do it.
class OwnedTable(tables.Table):
roles = tables.Column(empty_values=())
def render_roles(self):
user = self.context["request"].user
...
否则,@ mariodev的解决方案有效.
Otherwise, @mariodev's solution works.
这篇关于在django-tables2中显示多对多相关记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!