7

I have model with many links into it:

class Travel(BaseAbstractModel):

    tags = models.ManyToManyField(
        Tag,
        related_name='travels',
        )
    owner = models.ForeignKey(
        'users.TravelUser',
        related_name='travel_owner'
        )
    payment = models.ForeignKey(
        Payment,
        related_name='travels',
        )
    country = models.ForeignKey(
        Country,
        related_name='travels,
        )
    ........

Many of these models have only two fields with unique name and image. I create serializer for each of these models and put them in TravelSerializer

class TravelBaseSerializer(DynamicFieldsModelSerializer):

    owner = UserSerializer(required=False)
    tags = TagSerializer(many=True)
    payment = PaymentSerializer()
    country = CountrySerializer()  

Based on docs I override create() and update.
The problem is, when I sent JSON data, Django create each model from nested serializers. But I want to create only Travel instance. Also I want receive and respond serialized object not only pk field.

UPDATE
I solved this problem, put code in the answer. Now I can receive and respond with Serializer data without creating object. But I think the DRF provides more elegant approach then I do. It is my first project with DRF, maybe I miss something and there's an easier solution.

2 Answers 2

2

I decide override to_internal_value() put it in custom serailizer and inherit all nested serializers from it:

class NestedRelatedSerializer(serializers.ModelSerializer):

    def to_internal_value(self, data):
        try:
           pk = data['pk']
        except (TypeError, KeyError):
        # parse pk from request JSON
            raise serializers.ValidationError({'_error': 'object must provide pk!'})
        return pk

Get all pk from it and save in create and updated methods:

    def update(self, instance, validated_data):
        # If don't get instance from db, m2m field won't update immediately
        # I don't understand why
        instance = Travel.objects.get(pk=instance.pk)
        instance.payment_id = validated_data.get('payment', instance.payment_id)
        instance.country_id = validated_data.get('country', instance.country_id)
        # update m2m links
        instance.tags.clear()
        instance.tags.add(*validated_data.get('tags'))
        instance.save()
        return instance
1

I'm not exactly sure I understand what you want to do, but could setting read_only_fields is the Meta class be what you need ?

class TravelBaseSerializer(DynamicFieldsModelSerializer):

    owner = UserSerializer(required=False)
    tags = TagSerializer(many=True)
    payment = PaymentSerializer()
    country = CountrySerializer()  

    class Meta:
        read_only_fields = ('tags',)

See this section in the docs.

7
  • Thank you, but I tried it in the first thing. Problem with read_only_fields, these fields do not pass to validated_data Jul 23, 2016 at 17:31
  • OK so what I think you want is this: you want that when your serializer is used for reading puproses, it serializes all the related fields, and when used for writing puproses it tries to validate the related fields but not save them. Please correct me if I'm wrong.
    – AntoineWDG
    Jul 24, 2016 at 11:04
  • yes, but I need this data in validated_data, because I need to fill all link fields in created Travel model. I solve it, like you can see in my answer. But I start this bounty, because, I want to find some best practice, for purposes like this. Now I think, DRF just not allow use nested serializers for purposes like that, by default Jul 24, 2016 at 14:34
  • Again I'm not sure I understand exactly, you do not want the tags to be saved because they already exist and you only want the user to refer to existing tags using a primary key ? If so, you may want to take a look at PrimaryKeyRelatedField here django-rest-framework.org/api-guide/relations/….
    – AntoineWDG
    Jul 24, 2016 at 14:54
  • I note all of this in question and my answer below, I look at PKRelatedField, but problem was with to_representation of this field, I want work with serializer as usual, all my fk and m2m fields should represented by JSON object, not only pk. Jul 24, 2016 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.