29👍
✅
Thanks for all those who tried to answer. Got inspiration from the answer this link in case anyone gets into the same trouble as I did. Include intermediary (through model) in responses in Django Rest Framework.
class StyleSerializer(serializers.ModelSerializer):
colors = StyleColorSerializer(source='stylecolor_set',
many=True, read_only=True)
class Meta:
model = Style
fields = ('name', 'colors')
0👍
serializers.py
class ColorSerializer(serializers.ModelSerializer):
class Meta:
model = Color
fields = '__all__'
class StyleSerializer(serializers.ModelSerializer):
color = ColorSerializer() # each style has a set of colors attributed to it
class Meta:
model = Style
fields = '__all__'
class SizeSerializer(serializers.ModelSerializer):
class Meta:
model = Size
fields = '__all__'
class StyleColorSerializer(serializers.ModelSerializer):
size = SizeSerializer() # each style-color combination has a set of sizes attributed to it
class Meta:
model = StyleColor
fields = '__all__'
Because your models are too complex, I’m afraid the code above didn’t fit that well.
To be more general, if you wanna attach the queryset of B model at the same time when you fetch the queryset of A model (which has a relationship with B model), you have to define the BSerializer() in the class of ASerializer().
- In Django admin, how can I hide Save and Continue and Save and Add Another buttons on a model admin?
- How do I convert kilometres to degrees in Geodjango/GEOS?
Source:stackexchange.com