django-tables 2 M2M 字段未显示
django-tables 2 M2M field not shown
我正在尝试在 Django-tables2: How to use accessor to bring in foreign columns? and 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']
知道我做错了什么吗?
这对 ManyToManyFields
来说并不容易,因为 Accessor
的工作方式很简单。您可以通过 'lipids.all'
显示相关 QuerySet
的 repr
,但这在这里似乎还不够。但是,您可以将 属性(或方法)添加到 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')
添加到您传递给 table 的 Organism
QuerySet
以获得更好的性能。
我正在尝试在 Django-tables2: How to use accessor to bring in foreign columns? and 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']
知道我做错了什么吗?
这对 ManyToManyFields
来说并不容易,因为 Accessor
的工作方式很简单。您可以通过 'lipids.all'
显示相关 QuerySet
的 repr
,但这在这里似乎还不够。但是,您可以将 属性(或方法)添加到 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')
添加到您传递给 table 的 Organism
QuerySet
以获得更好的性能。