【问题标题】:Django Rest Framework gives wrong type serializer field type when derived from properties从属性派生时,Django Rest Framework 给出错误的类型序列化器字段类型
【发布时间】:2015-12-21 21:27:53
【问题描述】:

假设我有这个 CartItem 和 OrderItem 模型:

class CartItem(Model):
    price = DecimalField(..)


class OrderItem(Model):
    cartitem = OneToOneField('CartItem')

    @property
    def price(self):
        return self.cartitem.price

在使用ModelSerializer并让它隐式确定字段来渲染OrderItem时,价格字段变为浮点类型。

例如。 'price': 10.5 但我期待看到 'price': '10.5'

我需要在序列化程序中明确指定 DecimalField 以生成正确的十进制类型,如下所示:

class OrderItemSerializer(ModelSerializer):
    price = DecimalField(...)

我错过了什么吗?

更新:这是我在 github 上提出的问题: Django Rest Framework gives wrong type serializer field type when derived from properties

【问题讨论】:

  • 当您没有明确指定字段时,repr(OrderItemSerializer()) 会给出什么?
  • price = ReadOnlyField()
  • 你能分享更多细节吗:比如当前输出和想要的输出。
  • @DhiaTN 添加了输出和预期输出

标签: django serialization django-rest-framework


【解决方案1】:

基于 DRF 存储库中的 issue 582,从 2.1.16 版本开始,DecimalField 将返回字符串,但它也会更改值。

>>> from decimal import Decimal
>>> from rest_framework import renderers
>>> 
>>> obj = {'foo': ['bar', 'baz'], 'float': 1.1, 'decimal': Decimal(1.1)}
>>> 
>>> renderers.JSONRenderer().render(obj, 'application/json')
'{"float": 1.1, "decimal": "1.100000000000000088817841970012523233890533447265625", "foo": ["bar", "baz"]}'`

我会推荐使用自定义属性,而不是 DecimalField 使用 SerializerMethodField

class OrderItemSerializer(ModelSerializer):
    price = SerializerMethodField()

    def get_price(self, obj):
        return str(obj.price)

【讨论】:

  • er...我认为您的回答缺少这个问题提出的要点。
猜你喜欢
  • 2018-06-07
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
相关资源
最近更新 更多