Reputation: 341
I have a pallet that have contents inside. I need to assign a specific number to the pallet, based to a foreign key value (But that is not in the code yet).
With postman, when I POST with some json body;
Which is the correct way to achieve adding data before create? Here are the serializers:
class ContentSerializer(serializers.ModelSerializer):
class Meta:
model = models.Content
fields = ('id', 'quantity', 'kilograms', 'container')
class PalletSerializer(serializers.ModelSerializer):
contents = ContentSerializer(many=True)
class Meta:
model = models.Pallet
fields = ('id', 'number', 'receipt_waybill', 'client', 'contents',)
def create(self, validated_data):
contents_data = validated_data.pop('contents')
number = 123456
pallet = models.Pallet.objects.create(number=number, **validated_data)
for content_data in contents_data:
specifications_data = content_data.pop('specifications')
instance = models.Content.objects.create(pallet=pallet, **content_data)
instance.specifications.set(specifications_data)
return pallet
Upvotes: 0
Views: 375
Reputation: 1272
You can set the number
field to be read only. You can achieve that by either defining the field manually using number = serializers.IntegerField(read_only=True)
in your PalletSerializer
or by defining a read_only_fields = ('number',)
in your serializer's class Meta
.
Upvotes: 1