Axeltherabbit
Axeltherabbit

Reputation: 737

Django rest framework serializer object from ID

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?

Upvotes: 1

Views: 891

Answers (2)

Axeltherabbit
Axeltherabbit

Reputation: 737

Answering my own question.

Doing it was actually quite simple. It's just about a combination of using required=False in the serializer fields and calling the serializer with MySerializer(data=data, partial=True)

Upvotes: 0

Tushar
Tushar

Reputation: 1306

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.

Upvotes: 2

Related Questions