7
The solution is to define UserSerializer extending ModelSerializer like that
from rest_framework.serializers import ModelSerializer
class UserSerializer(ModelSerializer):
class Meta:
model = UserModel
fields = ['id', 'username']
and then use it in PostSerializer:
from myapp import UserSerializer
from rest_framework.serializers import ModelSerializer
class PostSerializer(ModelSerializer):
owner = UserSerializer()
class Meta:
model = PostModel
fields = ['id', 'owner']
2
Use the depth
option within your ModelSerializer
‘s Meta
class:
class PostSerializer(ModelSerializer):
class Meta:
model = Post
fields = ['text', 'owner']
depth = 1
Also note that you don’t need to include the Author
field.
Docs here.
- [Django]-Django official tutorial for the absolute beginner, absolutely failed!
- [Django]-How to define the admin import format for a field using django-import-export
Source:stackexchange.com