gpt4 book ai didi

python - 在 Django REST Framework 中公开 MoneyFields?

转载 作者:行者123 更新时间:2023-12-04 14:15:36 25 4
gpt4 key购买 nike

我有一些使用 djmoney.models.fields.MoneyField 的 Django 模型。这会存储诸如“1,000.00 美元”之类的数据。

我正在尝试通过 API 与 Django REST Framework 公开它直接在 Django 的管理员中使用自定义 View ,例如:

from rest_framework import generics
from rest_framework import serializers

class MyModelAdmin(admin.ModelAdmin):

def changelist_view_api(self, request, extra_context=None):

cl = self.get_changelist_instance(request)
base_queryset = cl.get_queryset(request)

fieldsets = self.get_fieldsets(request)

class ModelSerializer(serializers.ModelSerializer):

class Meta:
model = self.model
fields = all_fields

class ModelAdminListAPI(generics.ListCreateAPIView):
queryset = base_queryset
serializer_class = ModelSerializer

name = '%s List API' % self.model._meta.verbose_name.title()

def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)

view_handler = ModelAdminListAPI.as_view(queryset=base_queryset, serializer_class=ModelSerializer)
return view_handler(request, extra_context, format=_format)

这很好用,唯一的异常(exception)是它会阻塞这些特殊的 MoneyField 实例。对于字段列表中的其中一个,此 View 返回异常:

  File "~/.env/lib/python3.7/site-packages/rest_framework/mixins.py", line 43, in list
return self.get_paginated_response(serializer.data)
File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 761, in data
ret = super().data
File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 679, in to_representation
self.child.to_representation(item) for item in iterable
File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 679, in <listcomp>
self.child.to_representation(item) for item in iterable
File "~/.env/lib/python3.7/site-packages/rest_framework/serializers.py", line 530, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "~/.env/lib/python3.7/site-packages/rest_framework/fields.py", line 1148, in to_representation
value = decimal.Decimal(str(value).strip())
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

深入研究 DRF 的内部结构,它似乎将 MoneyField 视为 DecimalField,因为它是从中继承的。但是,djmoney 还创建了另一个名为 *_currency 的 CharField,用于存储货币面额(例如“USD”)。然后,当您请求货币字段的逻辑值时,它会将小数和货币值组合成格式“”。

我认为 DRF 在尝试将此值解释为小数时遇到了问题。

这是 DRF 中的错误还是我配置错误?如何允许 DRF 正确解释 MoneyField 值?

最佳答案

我有同样的问题,通过将 'djmoney', 添加到 INSTALLED_APPS 来解决。当您执行此操作时,MoneyField 将为转换和所有工作注入(inject)正确的序列化程序字段。喂:-)

关于python - 在 Django REST Framework 中公开 MoneyFields?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60662373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com