jplattus
jplattus

Reputation: 341

Edit fields before create using ModelSerializer

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;

  1. If I give some number field, then get an error that number cannot be duplicated.
  2. If I don't send number(because I'm giving it on customized create method), I get an error that number is a required field.
  3. If I remove number from PalletSerializer, it saves, but when I need to get it, there is no number to see.

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

Answers (1)

henriquesalvaro
henriquesalvaro

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

Related Questions