我有一個表Compounds
與name
字段,該字段鏈接到另一個表稱爲Names
。如何在django-tables2的訪問器字段中顯示對象的屬性,而不是對象本身?
當我用django-tables2渲染一張表時,它顯示得很好,除了它在name
列中沒有說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
結果:
謝謝。標記爲正確答案,一旦它讓我。 –