This is my output that should look like
{
"status": 1,
"errors": "",
"results": [
{
"car_type": "sedan",
"is_active": true,
"company": {
["tata","hyundai"]
}
}
]
}
And my model is,
class CarType(CommonBase):
car_type = models.TextField(null=True, blank=True)
is_active = models.BooleanField(default=True)
company = models.ManyToManyField('Company', null=True,
blank=True)
class Company(CommonBase):
company_name = models.TextField(null=True, blank=True)
country = models.TextField(null=True, blank=True)
how i should write my serialiser for a get API to return all car type with is_active = True
That
{
"company": {[...]}
}
dictionary thing in the company serialization doesn't make sense, instead what you want there is an actual list.
Focusing just on the item serialization in the results
you could use a serializer like:
class CarTypeSerializer(serializers.ModelSerializer):
company = serializers.SerializerMethodField()
def get_company(self, obj):
return [company.company_name for company in obj.company.all()]
class Meta:
model = CarType
fields = ("car_type", "is_active", "company")
which will yield an output like:
{
"car_type": "Car type..",
"is_active": true,
"company": [
"company 1",
"company 2"
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.