How to response different data that was inserted by create method (ModelViewSet)
I finally managed to sort this out, and in a much more elegant way than I had been trying beforehand.
What I need to do is: add new stock instances, for this I had created a new route for POST in the endpoint resources/id.
So I was able to reuse the Default Router, delete the custom_create
method, and just modified the serializers.py file.
It looks like this:
serializers.py
class StockSerializer(serializers.ModelSerializer):
class Meta:
model = Stock
fields = ['size', 'amount']
class ShoeSerializer(serializers.ModelSerializer):
stock = StockSerializer(many=True)
def update(self, instance, validated_data):
instance.description = validated_data.get(
'description', instance.description)
instance.provider = validated_data.get(
'provider', instance.provider)
instance.type = validated_data.get('type', instance.type)
instance.cost_price = validated_data.get(
'cost_price', instance.cost_price)
instance.salve_price = validated_data.get(
'sale_price', instance.sale_price)
stock = instance.stock.all()
stock_data = validated_data.get('stock', [])
for item_data in stock_data:
item_id = item_data.get('size', None)
if item_id is not None:
item_db = stock.get(size=item_id)
item_db.size = item_data.get('size', item_db.size)
item_db.amount = item_data.get('amount',item_db.amount)
item_db.save()
else:
Estoque.objects.create(
shoe = instance,
size = item_data['size'],
amount = item_data['amount']
)
instance.save()
return instance
class Meta:
model = Shoe
fields = ['_id','description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock']
Now, via PATCH
verb I can add new Stock instances and alter existing stock instances. Thank you for the support!
If I understood correctly by looking at your code, in this case specifically, you don't need the StockPostSerializer
. You can acheive the result you want by changing StockSerializer
as follows:
class StockSerializer(serializers.ModelSerializer):
class Meta:
model = Stock
fields = ['shoe', 'size', 'amount']
extra_kwargs = {'shoe': {'write_only': True}}
I greatly apologize if I misunderstood your question.
EDIT:
Forgot to say. Using this serializer you don't need any extra route on your ModelViewSet