【问题标题】:How to serialise model field verbose_name如何序列化模型字段verbose_name
【发布时间】:2020-01-14 16:27:13
【问题描述】:

我想创建一个可用于任何模型的通用 ListView 模板。

我目前正在使用这种方法来创建字段名称和值的dict

views.py

from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )

模板.html

{% for instance in data %}
    {% for field, value in instance.fields.items %}
        {{ field }}: {{ value }}
    {% endfor %}
{% endfor %}

这将返回字段但不返回字段verbose_name。例如,在用户模型上 is_active 不会返回为 Is the user active?

有没有办法也序列化详细名称?

【问题讨论】:

  • 在 shell 中尝试dir(obj) 其中objSomeModel 的对象
  • @ShashankSingh 谢谢,这对这个问题有什么帮助?

标签: django django-models django-serializer


【解决方案1】:

您可以使用受django.forms.model_to_dict启发的以下内容。

它从给定查询集的模型中检索字段,然后遍历查询集并使用.values_from_object() 检索每个实例的字段值。

使用f.verbose_name 而不是f.name 确定密钥。

from itertools import chain

def queryset_to_dict(queryset, include=None, exclude=None):
    """
    :param queryset: queryset of objects
    :param include: return only the named fields in each instance dict
    :param exclude: exclude the named from the instance dict even if listed in `fields`
    :return: list of dicts
    """
    opts = queryset.model._meta
    fields = []
    for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
        if not getattr(f, 'editable', False):
            continue
        if include is not None and f.name not in include:
            continue
        if exclude and f.name in exclude:
            continue

        fields.append(f)

    data = []
    for instance in queryset:
        instance_dict = {}
        for f in fields:
            key = f.verbose_name
            instance_dict[key] = f.value_from_object(instance)

        data.append(instance_dict)

    return data

示例用法:

queryset = Order.objects.filter(date_invoice__gte='2019-12-01')
data = queryset_to_dict(queryset, include=['id', 'date_invoice'])

【讨论】:

    【解决方案2】:

    将模型转换为字典并保留所有ForiegnKey 模型关系。我使用了以下内容:

    没有详细名称

    from django.forms.models import model_to_dict
    
    instance = MyModel.objects.get(pk=1) # EXAMPLE
    
    instance_dict = {key: getattr(instance, key) for key in model_to_dict(instance).keys()}
    

    输出

    {'foreign_key': [<OtherModel: OtherModel object>],
     'id': 1,
     'many_to_many': [<OtherModel: OtherModel object>],
     'normal_value': 1}
    

    如果您想在模板中为外键关系显示 __str__() 值,这会很有用。

    model_to_dict(instance, [...]) 中包含关键字参数fields=exclude= 使您能够过滤特定字段。

    带有详细名称

    from django.forms.models import model_to_dict
    
    instance = MyModel.objects.get(pk=1) # EXAMPLE
    
    instance_dict = {instance._meta.get_field(key).verbose_name if hasattr(instance._meta.get_field(key), 'verbose_name') else key: getattr(instance, key) for key in model_to_dict(instance).keys()}
    

    示例输出(如果给定示例有详细名称)

    {'Other Model:': [<OtherModel: OtherModel object>],
     'id': 1,
     'My Other Model:': [<OtherModel: OtherModel object>],
     'Normal Value:': 1}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-29
      • 2019-01-17
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多