Django Template:如何在values_list中显示Foreign Key的值

时间:2017-07-12 14:30:18

标签: django django-templates django-views

我将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>

无论如何我能保持代码的多功能性并显示外键对象的属性吗?

1 个答案:

答案 0 :(得分:1)

您可以使用双下划线表示法来访问遍历关系,类似于您在过滤器调用中的操作方式。如:

Class A:
    b = ForeignKey(B)

class B:
    description = CharField()

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

因此,对于您而言,您似乎要更改transaction_fields以在列表中包含'related_obj__field_needed'值。