Home > Back-end >  Django rest framework serializer object from ID
Django rest framework serializer object from ID

Time:10-27

I have this serializer:

class OrderLineSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source="item.id")
    name = serializers.ReadOnlyField(source="item.name")
    price = serializers.ReadOnlyField(source="item.price")
    quantity = serializers.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(MAXNUMBERSIZE)]
    )


    class Meta:
        model = OrderLine
        fields = ("id", "name", "price", "quantity", "sub_total")

and it's fine when I send data to the user but is there a way to serialize data that I receive from the API without creating another serializer.

if I receive some API request with this content

{id : 123, quantity : 10}

It doesn't get the item from the db.

is there a way to do it or I have to create a dedicated serializer?

CodePudding user response:

I believe a dedicated serializer is the way to go, first of all you won't want the complexity of using a single serializer. And it would only take 3 lines to build a new one for your input. So just make a dedicated serializer.

  • Related