Oleg Belousov
Oleg Belousov

Reputation: 10111

Django REST Framework set related field by another field than PK (without NestedSerializer)

I have the following serializer:

class OrderSerializer(serializers.ModelSerializer):
    pair_name = serializers.ReadOnlyField(source='pair.name', read_only=False)
    deposit_address = NestedReadOnlyAddressSerializer(many=False, read_only=True)
    withdraw_address = NestedAddressSerializer(many=False, read_only=False, partial=True)

pair.name is a unique field.

Is it possible to allow the PK assignment (order.pair) using the pair name.

[POST] {'withdraw_address': 'x', deposit: 'address': 'y', 'pair_name': 'ETHBTC'}

Instead of:

[POST] {'withdraw_address': 'x', deposit: 'address': 'y', 'pair': 1}

Tried looking thought the docs and did not find a solution. Googling for an hour did not help as well.

Currently lookup_field can only be set on ViewSet and not on Serializer.

Upvotes: 2

Views: 602

Answers (1)

Megan Cheesbrough
Megan Cheesbrough

Reputation: 56

Firstly, I don't think you want a write-only field if you want to be able to accept data for it.

For a good pattern to follow, look at Django REST Framework's documentation on writable nested serializers. http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

You will basically overwrite your serializer's create() and update() methods to handle setting the pair value appropriately.

Upvotes: 2

Related Questions