'MoneyField' object has no attribute 'serialize'

1k Views Asked by At

I have model Product with field MoneyField in /products/models.py

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")

My views.py is:

from .models import Product
from .serializers import ProductListSerializer
from rest_framework import generics

class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductListSerializer

and serializers.py:

from rest_framework import serializers
from .models import Product


class ProductListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = ['name', 'id']

and when i go to url i have error:

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'

Can you help me? Thank you!

1

There are 1 best solutions below

2
On

DRF's ModelSerializer assumes fields that are on the model extend django.db.models.fields.Field, which MoneyField does not. This is a problem when ModelSerializer is collecting fields:

# 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

You can fix the problem by subclassing MoneyField:

from django_prices.models import MoneyField as BaseMoneyField


class MoneyField(BaseMoneyField):
    serialize = True

This will probably lead to your next problem ;)