0
Hello,
I’m trying to assign data in a model that contains a Manytomany field...
Reading around I understood that first should instantiated the Model creating it and passing the data with exception of the Manytomany field.
I am rewriting the create() method but when I try to create initially the way I described, I continue with the same error, the following is displayed:
*** ValueError: "<Cart: XPTO>" needs to have a value for field "id" before this many-to-many relationship can be used.
Here is my code:
Model
from datetime import datetime
from clients.models import Client
from sellers.models import Seller
from itens.models import Item
from django.db import models
class Cart(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True)
seller = models.ForeignKey(Seller, on_delete=models.CASCADE, blank=True, null=True)
itens = models.ManyToManyField(Item, blank=True, null=True)
datetime = models.DateTimeField(auto_now_add=True)
total_value = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
commission = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
def __str__(self):
return str(self.client)
Serialize:
from products.models import Product
from itens.api.serializers import ItemSerializer
from itens.models import Item
from clients.models import Client
from clients.api.serializers import ClientSerializer
from carts.models import Cart
from rest_framework.serializers import ModelSerializer
class CartSerializer(ModelSerializer):
itens = ItemSerializer(many=True)
class Meta:
model = Cart
fields = '__all__'
def create(self, validated_data):
itens = validated_data['itens']
del validated_data['itens']
carts = Cart.objects.create(**validated_data)
I have also tried to remove other fields from the validated_data
as a seller and client to test, but I still have the same error.
It’s like I’m prevented from creating the object anyway.
Someone can give me a boost with that?
Thanks!