'MoneyField'对象没有属性'serialize'



我有型号Product,在/products/models.py中有字段MoneyField

class Product(SeoModel, ModelWithMetadata, PublishableModel):
name = models.CharField(max_length=128)
currency = models.CharField(
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
default=settings.DEFAULT_CURRENCY,
)
price_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
)
price = MoneyField(amount_field="price_amount", currency_field="currency")

我的views.py是:

from .models import Product
from .serializers import ProductListSerializer
from rest_framework import generics
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductListSerializer

serializers.py:

from rest_framework import serializers
from .models import Product

class ProductListSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['name', 'id']

当我转到url时,我有错误:

AttributeError at /ru/products/api/
'MoneyField' object has no attribute 'serialize'
Request Method: GET
Request URL:    http://127.0.0.1:8000/ru/products/api/
Django Version: 2.2.6
Exception Type: AttributeError
Exception Value:    
'MoneyField' object has no attribute 'serialize'

你能帮我吗?非常感谢。

DRF的ModelSerializer假定模型上的字段扩展django.db.models.fields.Field,而MoneyField没有。当ModelSerializer收集字段时,这是一个问题:

# rest_framework.utils.model_meta._get_fields
def _get_fields(opts):
fields = OrderedDict()
for field in [field for field in opts.fields if field.serialize and not field.remote_field]:
fields[field.name] = field
return fields

你可以通过将MoneyField:子类化来解决这个问题

from django_prices.models import MoneyField as BaseMoneyField

class MoneyField(BaseMoneyField):
serialize = True

这可能会导致您的下一个问题;(

相关内容

  • 没有找到相关文章

最新更新