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

Get foreign key unicode value in the template rather than its id

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

我的模型

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]

我的视图

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

和我的模板

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

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

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

对于外键,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]