Create() Argument After ** Must Be A Mapping, Not List, Django Rest Framework (implementing My Own Create Method Error)
when I am implementing this code-example on the documentation (I had to implement the create method myself because I have nested objects and inserting them is not supported by defa
Solution 1:
You're confusing various names here. You pop the categories
element from validated_data
, and assign it to product_data
; but it is not product data, it is a list of categories.
You then try and create a Product with that data related to an existing product - presumably you meant to create a Category there. But again what you have is a list, so you need to iterate through and create one category per entry.
And finally note that you have a many-to-many relationship between product and category, not a foreign key as in the example, so you can't use that product=product
syntax.
This would be better as:
def create(self, validated_data):
category_data = validated_data.pop('categories')
product = Product.objects.create(**validated_data)
for category in category_data:
product.categories.create(**category)
return product
(Although note that yes, creating nested items is supported by DRF; see the docs on serializer relations.)
Post a Comment for "Create() Argument After ** Must Be A Mapping, Not List, Django Rest Framework (implementing My Own Create Method Error)"