2017-07-12 14 views
0

values_listの外部キーIDをテンプレートに渡しているので、テンプレートに参照されているオブジェクトのIDのみが表示されます。明示的にフィールドを渡すことなく、実際のオブジェクトを取得したいと思います。Djangoテンプレート:values_listに外部キーの値を表示する方法

models.py:

class Transaction(models.Model): 
''' This class will host RBC raw data. ''' 
    account_type = models.CharField(max_length = 20) 
    account_number = models.CharField(max_length = 20) 
    transaction_date = models.DateField() 
    cheque_number = models.CharField(max_length = 20, null = True, blank = True) 
    description_1 = models.CharField(max_length = 100, null = True, blank = True) 
    description_2 = models.CharField(max_length = 100, null = True, blank = True) 
    cad = models.DecimalField(max_digits = 10, decimal_places = 2, blank = True, null = True) 
    usd = models.DecimalField(max_digits = 10, decimal_places = 2, blank = True, null = True) 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank = True, null = True, on_delete = models.PROTECT) 
    category = models.ForeignKey('BudgetCategory', blank = True, null = True, on_delete = models.PROTECT) # same as above comment 
    subcategory = models.ForeignKey('BudgetSubCategory', blank = True, null = True, on_delete = models.PROTECT) # Does not delete related sub-categories if a transaction is delted. 

views.py:

transaction_fields = ['account_type', 'account_number', 'transaction_date', 'description_1', 'description_2','cad', 'category', 'subcategory'] 
field_order_by = ['category', 'subcategory', 'description_1', 'transaction_date'] 

class AllRecordsView(ListView): 
    template_name = 'index.html' 
    context_object_name = 'transactions' 

    fields = transaction_fields 
    field_order_by = field_order_by 
    def get_queryset(self, *args, **kwargs): 

     transactions = Transaction.objects.all().values_list(*self.fields).order_by(*field_order_by) 

     return transactions 


    def get_context_data(self, **kwargs): 
     context = super(AllRecordsView, self).get_context_data(**kwargs) 

     column_fields = fields_to_columns(self.fields) # returns the name of columns in capitalized form and changing underscore to space 
     context['fields'] = column_fields    # Adding a context variable called field which hosts the column names list 
     return context 

テンプレート:つまり

{% for transaction in transactions %} 
     <tr> 
      {% for field in transaction %} 
       <td> {{ field }} </td> 
     </tr> 

、私はすべてのトランザクションオブジェクトを渡すことを避けるためにしようと呼び出しています各フィールドは別々に:

<tr> 
{% for transaction in transactions %} 
    <td> {{ transaction.account_type }} </td> 
    ... 
    <td> 
     {{ transaction.category.name }} 
    </td> 
{% endfor %} 
</tr> 

私はコードの汎用性を維持し、外部キーオブジェクトの属性を表示できますか?

答えて

1

フィルタ呼び出しでの操作と同様の二重アンダースコア表記を使用して、トラバース関係にアクセスできます。以下のような:

Class A: 
    b = ForeignKey(B) 

class B: 
    description = CharField() 

A.objects.all().values_list('b__description') 

リストに'related_obj__field_needed'値を含めるようにtransaction_fieldsを変えたいように思えるあなたのためのようにします。

関連する問題