python - How to serialize related models in Django Rest API? -
i have tried solutions. still cannot resolve it. here codes.
models.py
class car(models.model): car_name = models.charfield(max_length=250) car_description = models.charfield(max_length=250) def __str__(self): return self.car_name + ' - ' + str(self.pk) class owners(models.model): car = models.foreignkey(car, on_delete=models.cascade, default=0) owner_name = models.charfield(max_length=250) owner_desc = models.charfield(max_length=250) def get_absolute_url(self): return reverse('appname:index') def __str__(self): return self.owner_name + ' - ' + self.owner_desc
serializers.py
class ownersserializer(serializers.modelserializer): class meta: model = owners fields = '__all__' class carserializer(serializers.modelserializer): owners = ownersserializer(many=true, read_only=true) class meta: model = car fields = '__all__'
views.py
class carlist(apiview): def get(self, request): cars = car.objects.all() serializer = carserializer(cars, many=true) return response(serializer.data) def post(self): pass
i can't view 'owner' objects related object of 'car' class.
you need define related name on foreignkey create reverse reference.
class owners(models.model): car = models.foreignkey(car, on_delete=models.cascade, default=0, related_name='owners')
Comments
Post a Comment