如何在django-tables2的访问器字段中显示对象的属性,而不是对象本身?

时间:2017-06-06 20:25:47

标签: django django-tables2

我有一个rake test表,其中Compounds字段与另一个名为name的表相关联。

当我使用django-tables2呈现一个表格时,它显示得很好,除了它在Names列中没有说出aspirin的事实,它说name

Name object

models.py

class Compound(models.Model): drug_id = models.AutoField(primary_key=True) drug_name = models.ForeignKey(Name, db_column='drug_name', null=True, on_delete=models.PROTECT) # for flagging problematic data flag_id = models.ForeignKey(Flag, db_column='flag_id', null=True, on_delete=models.PROTECT) # is a cocktail is_combination = models.BooleanField() class Meta: db_table = 'compounds'

tables.py

import django_tables2 as tables from .models import Compound class FimTable(tables.Table): drug_name = tables.Column(accessor='name.name') class Meta: model = Compound attrs = {'class': 'paleblue table table-condensed table-vertical-center'} fields = ('drug_id', 'drug_name') sequence = ('drug_id', 'drug_name') order_by = ('drug_id')

views.py

结果:

The resulting table. Notice that it says "Name Object" instead of the name itself.

2 个答案:

答案 0 :(得分:1)

您只需要在Name对象上定义__str__方法。

class Name(models.Model):
    ...

    def __str__(self):
        return self.name

答案 1 :(得分:0)

你也可以使用......

class Name(model.Model):
      ...
      def __unicode__(self):
          return self.name