迭代模板中的模型实例字段名称和值 [英] Iterate over model instance field names and values in template

查看:31
本文介绍了迭代模板中的模型实例字段名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基本模板来显示所选实例的字段值及其名称.可以将其视为表格式的该实例值的标准输出,第一列中为字段名称(如果在字段中指定了详细名称),第二列中为该字段的值.

I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column.

例如,假设我们有以下模型定义:

For example, let's say we have the following model definition:

class Client(Model):
    name = CharField(max_length=150)
    email = EmailField(max_length=100, verbose_name="E-mail")

我希望它像这样在模板中输出(假设一个具有给定值的实例):

I would want it to be output in the template like so (assume an instance with the given values):

Field Name      Field Value
----------      -----------
Name            Wayne Koorts
E-mail          waynes@email.com

我想要实现的是能够将模型的实例传递给模板,并能够在模板中动态迭代它,如下所示:

What I'm trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this:

<table>
    {% for field in fields %}
        <tr>
            <td>{{ field.name }}</td>
            <td>{{ field.value }}</td>
        </tr>
    {% endfor %}
</table>

是否有一种简洁的、Django 认可的"方式来做到这一点?这似乎是一项很常见的任务,我需要经常为这个特定项目做这件事.

Is there a neat, "Django-approved" way to do this? It seems like a very common task, and I will need to do it often for this particular project.

推荐答案

model._meta.get_all_field_names() 会给你所有模型的字段名称,然后你就可以使用 model._meta.get_field() 以自己的方式获取详细名称,并使用 getattr(model_instance, 'field_name') 从模型中获取值.

model._meta.get_all_field_names() will give you all the model's field names, then you can use model._meta.get_field() to work your way to the verbose name, and getattr(model_instance, 'field_name') to get the value from the model.

注意:model._meta.get_all_field_names() 在 django 1.9 中已弃用.而是使用 model._meta.get_fields() 获取模型的字段并使用 field.name 获取每个字段名称.

NOTE: model._meta.get_all_field_names() is deprecated in django 1.9. Instead use model._meta.get_fields() to get the model's fields and field.name to get each field name.

这篇关于迭代模板中的模型实例字段名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆