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.