我有两种模式:
class User(models.Model):
username = models.CharField()
和
class Post(models.Model):
text = models.TextField()
owner = models.ForeignKey(User)
使用这样的序列化器:
from rest_framework.serializers import ModelSerializer
class PostSerializer(ModelSerializer):
owner = serializers.Field(source='owner.id')
class Meta:
model = Post
fields = ['text', 'owner']
我收到了所有者ID的所有帖子。如何修改序列化程序以获取包含整个用户模型的所有者fialed的所有帖子?
我试过了 来自rest_framework.serializers导入ModelSerializer
class PostSerializer(ModelSerializer):
owner = serializers.Field(source='owner')
class Meta:
model = Post
fields = ['text', 'owner']
但是只用id替换了id,而不是我预期的整个模型(因为User的表示返回了username字段)。
答案 0 :(得分:6)
解决方案是定义UserSerializer,像那样扩展ModelSerializer
from rest_framework.serializers import ModelSerializer
class UserSerializer(ModelSerializer):
class Meta:
model = UserModel
fields = ['id', 'username']
然后在PostSerializer中使用它:
from myapp import UserSerializer
from rest_framework.serializers import ModelSerializer
class PostSerializer(ModelSerializer):
owner = UserSerializer()
class Meta:
model = PostModel
fields = ['id', 'owner']
答案 1 :(得分:2)
使用depth
ModelSerializer
课程中的Meta
选项:
class PostSerializer(ModelSerializer):
class Meta:
model = Post
fields = ['text', 'owner']
depth = 1
另请注意,您不需要包含Author
字段。
文档here。