0

I have two models Category and Products, and a classic one to many relatoin between them. Each product belongs to a category.

I am using Django-Rest-Framework.

I am using ModelViewSet as a ViewSet and ModelSerializer as a Serializer.

I created the ProductViewSet which has the full CRUD opertions.

What I am trying to achieve is to include the relation in the READ operations ( list , retrieve ). The response should look something like that.

{
  "id" : 2,
  "name" : "foo product" , 
   "category" : {
     "id" : 4, 
     "name" : "foo relation" 
  }
}

So I set the depth field in Meta equal to 1.

class ProductSerializer(ModelSerializer):

    class Meta:
        model = Product
        exclude = ('createdAt',)
        depth = 1

What makes the category read only.But I want it to be writable in the other actions (POST , PUT).

I know I can solve the problem using two serializes but this is a repetitive problem and I don't want to write two serializes for each model I have.

I tried to add category_id field in the serializer but I had to override the create method to make it work correctly. And again I am trying to write less code. because I would end up overriding all of the app serializers.

class ProductSerializer(ModelSerializer):

    category_id = PrimaryKeyRelatedField(queryset=Category.objects.all())

    class Meta:
        model = Product
        exclude = ('createdAt',)
        depth = 1

    def create(self, validated_data):
        category_id = validated_data.pop('category_id').id
        validated_data['category_id'] = category_id
        return super().create(validated_data)

This is my first Django framework and I am trying to make it as neat as possible.

Rami ZK
  • 510
  • 3
  • 13
  • Have you tried looking at the [DRF documentation on writeable nested serializers](https://stackoverflow.com/a/27585066/2715819)? There are also lots of SO answers on the topic, e.g. [this one](https://stackoverflow.com/a/27585066/2715819) is from a few years ago, but a pretty good discussion. – RishiG Jul 10 '19 at 16:05
  • As I said I am trying not to write serializer for each relation as this is a repetitive problem. – Rami ZK Jul 10 '19 at 16:43

0 Answers0