gpt4 book ai didi

django - 使用与 django-rest-framework 序列化程序的反向关系

转载 作者:行者123 更新时间:2023-12-01 08:10:22 24 4
gpt4 key购买 nike

我的模型看起来像这样:

class User(TimestampedModel):
name = models.CharField(max_length=30, null=False, blank=False)
device = models.CharField(max_length=255, null=False, blank=False)


class Comment(TimestampedModel):
user = models.ForeignKey(User, on_delete=models.PROTECT, blank=True, null=True)
contents = models.CharField(max_length=510)
rating = models.IntegerField(blank=False, null=False)

我的序列化程序如下所示:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('name',)


class CommentListItemSerializer(serializers.ModelSerializer):
user = UserSerializer()

class Meta:
model = Comment
fields = ('user', 'contents', 'rating')

和观点:
class CommentsList(generics.ListAPIView):
serializer_class = CommentListItemSerializer
queryset = Comment.objects.all()

它几乎完成了工作;)。我得到的回应是这样的:
"results": [
{
"user": {
"name": "Ania"
},
"contents": "Very good",
"rating": 6
},
{
"user": {
"name": "Anuk"
},
"contents": "Not very good",
"rating": 1
}
]

这种 react 有两个问题。
  • 我不想拥有这个嵌套对象“user.name”。我想将其作为一个简单的字符串字段接收,例如 "username" .
  • 序列化程序为每个用户进行数据库查询(不是连接,而是单独的查询),以获取他/她的姓名。既然这是 Not Acceptable ,如何解决这个问题?
  • 最佳答案

    Serializer makes a database query (not a join, but a separate query) for each user, to get his/her name.



    您可以 使用 select_related() queryset 你的观点的属性。然后访问 user.name不会导致进一步的数据库查询。
    class CommentsList(generics.ListAPIView):
    serializer_class = CommentListItemSerializer
    queryset = Comment.objects.all().select_related('user') # use select_related

    I don't want to have this nested object "user.name". I'd like to receive that as a simple string field, for example "username"



    您可以 定义只读 username您的序列化程序中的字段 source 争论。这将返回 username场响应。
    class CommentListItemSerializer(serializers.ModelSerializer):
    # define read-only username field
    username = serializers.CharField(source='user.name', read_only=True)

    class Meta:
    model = Comment
    fields = ('username', 'contents', 'rating')

    关于django - 使用与 django-rest-framework 序列化程序的反向关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38139378/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com