获取模板中的外键unicode值而不是其id

时间:2017-03-05 11:05:57

标签: django django-templates foreign-keys detailview

我的模型由ForeignKey组成,我使用generics.DetailView在django视图中渲染对象详细信息。

为MyModel

class MyModel(models.Model):
    myField = models.ForeignKey(...)

    def get_fields(self):
        # called by the template
        return [(field.verbose_name, field.value_to_string(self)) for field in type(self)._meta.fields]

MyView的

class Detail(DetailView):
    model = MyModel
    template_name = 'path/to/template.html'

    def get_context_data(self, **kwargs):
        context = super(Detail, self).get_context_data(**kwargs)
        # do something
        return context

和MyTemplate

{% for field, value in object.get_fields %}
           <tr>
               <th>{{ field }}</th>
               <td>{{ value }}</td>
           </tr>
{% endfor %}

现在,当模板呈现时,我得到的是id而不是__unicode__表示。同样的问题也出现在ChoiceField中(我得到的是价值而不是他们的标签)。

所以我的问题是,如何获得标签或unicode表示而不是实际值?

1 个答案:

答案 0 :(得分:0)

对于ForeignKeys,getattr(self, field.name)似乎正在运作。所以:

class MyModel(models.Model):
    myField = models.ForeignKey(...)

    def get_fields(self):
        # called by the template
        return [(field.verbose_name, unicode(getattr(self, field.name))) for field in type(self)._meta.fields]

对于ChoiceFields,标签可以检索为self.get_<field_name>_display()。所以,在一起,也许像是

class MyModel(models.Model):
    myField = models.ForeignKey(...)

    def get_field_value(self, field):
        if isinstance(field, models.CharField) and field.choices:
             return getattr(self, 'get_{}_display'.format(field.name))()
        return unicode(getattr(self, field.name))

    def get_fields(self):
        # called by the template
        return [(field.verbose_name, self.get_field_value(field)) for field in type(self)._meta.fields]