I have some models and they are nested each others. I want to make a bulk create for 2 serializers , both have relations with other models. I looked at documentation on DRF but could not implement it in my code.
I send my json data like this:
{
'status':true,
'products':[
{
'painting':{'amount':10},
'product':{'id':12, }
},
{
'painting':{'amount':10},
'product':{'id':12, }
}
],
'customer':{ 'name':'Adnan',
'address':{'country':'Turkey'}
},
'total':111
}
#models.py
class Address():
...
class Customer():
address = models.ForeignKey(Address, ...)
class Painting():
...
class Product():
...
class Selling():
customer = models.ForeignKey(Customer, ...)
products = models.ManyToManyField(Product, through='SellingProduct')
class SellingProduct():
selling = models.ForeignKey(Selling, ...)
product = models.ForeignKey(Product, ...)
painting = models.ForeignKey(Painting, ...)
Here is my serializers.py
class AddressSerializer():
...
class CustomerSerializer():
address = AddressSerializer()
...
class PaintingSerializer():
...
class ProductSerializer():
...
class SellingProductSerializer():
painting = PaintingSerializer()
product = ProductSerializer()
class SellingSerializer():
customer = CustomerSerializer()
products = SellingProductSerializer(many=True)
...
def create(self, validated_data):
...
If I write this:
class SellingSerializer():
...
def create(self, validated_data):
customer_data = validated_data.pop('customer')
products_data = validated_data.pop('products')
selling = Selling.objects.create(**validated_data) #i didn't pass customer here
for product_data in products_data:
SellingProducts.objects.create(selling=selling, **product_data)
return selling
I'm getting this error:
django.db.utils.IntegrityError: (1048, "Column 'customer_id' cannot be null")
If I write this:
class SellingSerializer():
...
def create(self, validated_data):
selling = Selling.objects.create(**validated_data) #i didn't pass customer here
return selling
I'm getting this error:
ValueError: Cannot assign "OrderedDict...
..Selling.customer must be a "Customer" instance
- I don't know how to extract or access data if its type is OrderedDict. How can I do this also?
I want to create a record for Selling and SellingProduct, Painting and I DON'T want to create Customer, Address, Product records in every request and I will use existence(in front-end selected) datas.
Thank you all in advance for any help!