【发布时间】:2017-12-17 01:15:05
【问题描述】:
我将 values_list 中的外键 id 传递给模板,因此我的模板只能显示引用对象的 id。我想在没有明确传递字段的情况下获得实际对象。
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>
我是否可以保持代码的多功能性并显示外键对象的属性?
【问题讨论】:
标签: django django-templates django-views