I have two models namely:
class B (models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=255)
class A (models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=255)
b = models.ForeignKey(B,on_delete=models.CASCADE,null=True)
I want a serializer which returns a response like this:
{
"id": 1,
"name": "test",
"b_id": 2,
"b_name": "test
}
CodePudding user response:
the response format you want to get is not possible to my knowledge but you can use nestedSerializers
to get both models in one response like
{
"id": 1,
"name": "test",
"b":{
"id":"test",
"name": "test"
}
}
if this is enough for you you can use the following code
serializers.py
class Bserializer(serializers.ModelSerializer):
class Meta:
model = B
fields = "__all__" #or only the fields you want
class Aserializer(serializers.ModelSerializer):
b = Bserializer()
class Meta:
model = B
fields = ["id","name", "b"]
CodePudding user response:
Since b
field in A
model is a one to many relation so it should be a list of a items like this, also check docs
{
"b_id": 1,
"b_name": "test",
"a": [
'a_id1': 'a_name',
'a_id2': 'a_name'
]
}
If that is what you want you can do it like this:
class BSerializer(serializers.ModelSerializer):
a = serializers.StringRelatedField(many=True)
class Meta:
model = Album
fields = ['id', 'name', 'a']
CodePudding user response:
This is directly from a project im working on now
class CoachLocationsSerializer(serializers.ModelSerializer):
base = LocationSerializer(read_only=True)
locations = LocationSerializer(read_only=True, many=True)
class Meta:
model = Coach
fields = ['base', 'locations']