Django MoneyField: неверное значение для MoneyField - PullRequest
1 голос
/ 01 мая 2020

У меня небольшая проблема при использовании MoneyField в Django.

У меня есть 2 модели: Work и Price. И Price получает Work id в качестве внешнего ключа.

В Почтальоне я пытаюсь опубликовать Work с Price, но получаю сообщение об ошибке.

Вот мой work_model:

from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()

class Work(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=200)
    length = models.IntegerField(null=True)
    width = models.IntegerField(null=True)

    def __str__(self):
        return "{}".format(self.name)

А вот мой price_model

from django.db import models
from .model_work import *
from djmoney.models.fields import MoneyField

class Price(models.Model):
    work = models.OneToOneField(Work, on_delete=models.CASCADE, related_name='price')
    price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True)
    shipping = models.IntegerField(null=True)
    total = models.IntegerField(null=True)

    def __str__(self):
        return "{}".format(self.price)

Когда я публикую Work в Почтальоне:

{
    "user":"2",
    "name":"work 20",
    "price": 
        [
            {
                "price":20,
                "price_currency":"USD",
                "shipping":12,
                "total":32
            }
        ],
    "length":"50",
    "width":"60"
}

Я получаю эту ошибку:

ValidationError at /works/
["Invalid value for MoneyField: [OrderedDict([('price', <Money: 20.0000 USD>), ('shipping', 12), ('total', 32)])]."]

Я искал повсюду, но не могу понять мою ошибку, кто-нибудь есть подсказка?

Спасибо за ваши ответы!

ОБНОВЛЕНИЕ 1: Забыл поставить serializers.

Вот мой work_serializer:

from rest_framework import serializers
from ..models.model_work import Work
from .serializers_user import *
from .serializers_price import *


class WorkIndexSerializer(serializers.ModelSerializer):
    """
    Serializer listing all Works models from DB
    """
    user = UserIndexSerializer()
    price_set = PriceDetailsSerializer(many=True)

    class Meta:
        model = Work
        fields = [
            'id',
            'name',
            'price_set',
            'length',
            'width',
        ]

class WorkCreateSerializer(serializers.ModelSerializer):
    """
    Serializer to create a new Works model in DB
    """

    price = PriceCreateSerializer(many=True)

    class Meta:
        model = Work
        fields = [
            'user',
            'name',
            'price',
            'length',
            'width',
        ]

    def create(self, validated_data):
        price = Price.objects.create(**validated_data)
        work = Work.objects.create(**validated_data)

        return work


class WorkDetailsSerializer(serializers.ModelSerializer):
    """
    Serializer showing details of a Work model from DB
    """
    user = UserIndexSerializer()

    class Meta:
        model = Work
        fields = fields = [
            'user',
            'name',
            'price_set',
            'length',
            'width',
        ]

И мой price_serializer:

from rest_framework import serializers
from ..models.model_price import Price

class PriceIndexSerializer(serializers.ModelSerializer):
    """
    Serializer showing Price information when called by Work GET serializers.
    Not showing 'work' field to avoid loop.
    """
    class Meta:
        model = Price
        fields = [
            'price',
            'shipping',
            'total'
        ]
        depth = 1

class PriceDetailsSerializer(serializers.ModelSerializer):
    """
    Serializer showing Price information when called by Work GET serializers.
    Not showing 'work' field to avoid loop.
    """
    class Meta:
        model = Price
        fields = [
            'price',
            'shipping',
            'total'
        ]
        depth = 1

class PriceCreateSerializer(serializers.ModelSerializer):
    """
    Serializer to create a new Price when new Work model is created in DB
    """

    class Meta:
        model = Price
        fields = [
            'price',
            'shipping',
            'total'
        ]

    def create(self, validated_data):
        work = Work.objects.create(**validated_data)

        return work
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...