2017-06-06 39 views
0

我有一個表Compoundsname字段,該字段鏈接到另一個表稱爲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 

結果:

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

回答

1

您只需要在Name對象上定義__str__方法。

class Name(models.Model): 
    ... 

    def __str__(self): 
     return self.name 
+0

謝謝。標記爲正確答案,一旦它讓我。 –

0

您還可以使用...

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

如果你能詳細說明'__str__'和'__unicode__'之間的區別以及爲什麼會使用其中一個,那將會很有幫助。 – Jieter

相關問題