我如何在 django-tables2 的访问器字段中显示对象的属性,而不是对象本身?
How do i show an attribute of an object, rather than the object itself, in an accessor field in django-tables2?
我有一个 Compounds
的 table 和一个 name
字段,它链接到另一个名为 Names
的 table。
当我用 django-tables2 渲染 table 时,它显示得很好,除了它在 [=14= 中没有说 aspirin
] 列,上面写着 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
:
@csrf_protect
@login_required # redirects to login page if user.is_active is false
def render_fim_table(request):
table = FimTable(Compound.objects.all())
table.paginate(page=request.GET.get('page', 1), per_page=20)
response = render(request, 'fim_table.html', {'table': table})
return response
结果:
您只需要在 Name 对象上定义 __str__
方法。
class Name(models.Model):
...
def __str__(self):
return self.name
你也可以使用...
class Name(model.Model):
...
def __unicode__(self):
return self.name
我有一个 Compounds
的 table 和一个 name
字段,它链接到另一个名为 Names
的 table。
当我用 django-tables2 渲染 table 时,它显示得很好,除了它在 [=14= 中没有说 aspirin
] 列,上面写着 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
:
@csrf_protect
@login_required # redirects to login page if user.is_active is false
def render_fim_table(request):
table = FimTable(Compound.objects.all())
table.paginate(page=request.GET.get('page', 1), per_page=20)
response = render(request, 'fim_table.html', {'table': table})
return response
结果:
您只需要在 Name 对象上定义 __str__
方法。
class Name(models.Model):
...
def __str__(self):
return self.name
你也可以使用...
class Name(model.Model):
...
def __unicode__(self):
return self.name