14👍
Try this:
from rest_framework import serializers
from api_v1.models import Outlet, Address
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = ('building', 'street',)
depth = 3
class OutletSerializer(serializers.ModelSerializer):
address = AddressSerializer(many=False) # make it address, not outlet_address
class Meta:
model = Outlet
fields = ('id', 'name', 'thumbnail', 'address') # make this address as well, not outlet_address
depth = 3
The reason I would make the changes above is because the Outlet model does not have an attribute called “outlet_address”, it has an attribute called “address”.
See here for a similar issue: Django Rest framework keeps returning error on nested relationship
13👍
Additionally to the other answers, I would like to add the following in case somebody lands here too.
The nested serialization requires the field name to be in the model fields in order to work.
In case that we need a reverse relation, then obviously there will be no such field in the model fields.
For example, with the particular models in the question, this would happen if we needed to reference all outlets in the address serializer.
Therefore we need to: (a) Either specify a related_name
to the foreign key of the other model. This is where we would use outlet_address
, as this is the related name of address field in outlet model.
Or (b) if no related name then use the default Django name, appending _set
to the model name (eg outlet_set
.
- Registered models do not show up in admin
- Django redirect to another view with context
- Is the Global Request variable in Python/Django available?
- Postgres: values query on json key with django
3👍
Model Outlet has an “address” field, not an outlet_address. I would advise to set your serializer like this:
class OutletSerializer(serializers.ModelSerializer):
address = AddressSerializer(many=False)
class Meta:
model = Outlet
fields = ('id', 'name', 'thumbnail', 'address')
depth = 2
- PyCharm include and modify External library in project
- SerializerClass field on Serializer save from primary key
- How do I handle file upload via PUT request in Django?
- Django: What's the use of the context_instance parameter in the render shortcut function?
- Django and Shibboleth