我有这些模特:
class Category(models.Model):
name = models.CharField(max_length=10)
uuid = models.CharField(max_length=36)
class Item(models.Model):
name = models.CharField(max_length=255)
uuid = models.CharField(max_length=36)
categories = models.ManyToManyField(Category, null=True)
brand = models.ForeignKey(Brand)
我试图用django-tables2在表格中显示Item
模型,如下所示:
class ItemTable(tables.Table):
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ("uuid", "name", "brand", "categories")
categories = tables.Column(empty_values=())
def render_categories(self, value):
return ', '.join([category.name for category in value.all()])
它工作正常,但Table
忽略categories
字段和。{
value
参数等于None
,我收到错误'NoneType' object has no attribute 'all'
我做错了什么?感谢。
答案 0 :(得分:2)
这样做:
class ItemTable(tables.Table):
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ("uuid", "name", "brand", "categories")
categories = tables.Column()
def render_categories(self, value):
if value is not None:
return ', '.join([category.name for category in value.all()])
return '-'
答案 1 :(得分:0)
当使用django 1.7时,看起来这是django-tables2中的错误: https://github.com/bradleyayers/django-tables2/issues/211
答案 2 :(得分:0)
看起来它还没有被合并。作为一种解决方法,你可以使用记录进行渲染并以相同的方式迭代。
即
def render_categories(self, record):
if record.category is not None:
return ', '.join([category.name for category in record.category.all()])
return '-'
答案 3 :(得分:0)
也许不是更清洁的选择,但这对我有用:
class Item(models.Model):
name = models.CharField(max_length=255)
uuid = models.CharField(max_length=36)
categories = models.ManyToManyField(Category, null=True)
brand = models.ForeignKey(Brand)
@property
def categories_str(self):
return ', '.join([category.name for category in value.all()])
class ItemTable(tables.Table):
categories = tables.Column(accessor='categories_str')
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ("uuid", "name", "brand", "categories")
答案 4 :(得分:-1)
执行此操作:
class ItemTable(tables.Table):
class Meta:
model = Item
attrs = {"class": "paleblue"}
fields = ("uuid", "name", "brand", "categories")
categories = tables.Column(empty_values=())
def render_categories(self, record):
if record.categories.all():
return ', '.join([category.name for category in record.categories.all()])
return '-'
请注意,empty_values =()对于写入tables.Column()
非常重要