Although I am big fan of django rest framework but sometime i feel it is gruesome to deal with nested serializers (Maybe I am doing something wrong, feel free to suggest me your favourite trick.)
Suppose we have two models, ASerializer
is based on A
model, BSerializer
is based on `B` model. A
and B
models are related, say B
has a foreign key to A
. So while creating B
it is mandatory to define A
but A
serializer is full of so much data that I don’t want to have that unnecessary overhead at my BSerializer
, but when creating B
I must have it. Here how I solved it:
For the sake of brevity let’s say A
is our Category
, and B
is Product
. Every Product
has a Category
, so Product
has a foreign key of Category
, but I am not making it visible at ProductSerializer
given that category has a lot of unnecessary information that is not necessary.
from django.shortcuts import get_object_or_404 class ProductSerializer(serializers.ModelSerializer): def to_internal_value(self, data): if data.get('category'): self.fields['category'] = serializers.PrimaryKeyRelatedField( queryset=Category.objects.all()) cat_slug = data['category']['slug'] cat = get_object_or_404(Category, slug=cat_slug) data['category']= cat.id return super().to_internal_value(data)