我正在尝试在Django-tables2: How to use accessor to bring in foreign columns?和Accessing related models with django-tables2
中显示django-table2中的M2M字段使用:foreigncolumn = tables.Column(accessor =' foreignmodel.foreigncolumnname'),我只看到' - ' ...
# The models:
class Organism(models.Model):
species_name = models.CharField(max_length=200)
strain_name = models.CharField(max_length=200)
eukaryotic = models.BooleanField(default=True)
lipids = models.ManyToManyField('Lipid',blank=True)
class Lipid(models.Model):
lm_id = models.CharField(max_length=100)
common_name = models.CharField(max_length=100,blank=True)
category = models.CharField(max_length=100,blank=True)
#The tables
class OrganismTable(tables.Table):
name = tables.LinkColumn('catalog:organism-detail', text=lambda record: record.species_name, args=[A('pk')])
lp = tables.Column(accessor='Lipid.common_name')
class Meta:
model = Organism
sequence = ['name','lp']
exclude = ['id','species_name']
知道我做错了吗?
答案 0 :(得分:1)
由于ManyToManyFields
工作的简单方式,Accessor
对此工作起来并不那么容易。您可以通过repr
显示相关QuerySet
的{{1}},但这似乎不够。但是,您可以向'lipids.all'
模型添加属性(或方法),并在访问者中使用它。这样,您可以显示与实例相关的任何自定义信息:
Organism
我建议您将class Organism(models.Model):
# ...
@property
def lipid_names(self):
return ', '.join(l.common_name for l in self.lipids.all()) # or similar
class OrganismTable(tables.Table):
# ...
lp = tables.Column(accessor='lipid_names')
添加到传递给表格的prefetch_related('lipids')
Organism
,以获得更好的效果。