gpt4 book ai didi

python - Django Rest - 在 get_*** 方法中包含序列化器对象

转载 作者:行者123 更新时间:2023-12-01 04:39:16 34 4
gpt4 key购买 nike

我试图将相关模型的序列化对象包含在另一个序列化程序的自定义对象中,但我不知道如何执行此操作。

我有两个模型 - 代码片段和用户。片段模型具有用户的外键。我需要的是将代码片段的序列化对象包含在 UserSerializer 的“get_included”方法中,并使 UserSerializer 返回一个 JSON 对象,如下所示:

{
"id" : 1,
"included": [
{'id': 2,'created': "20150729" },
{'id': 3,'created': "20150730" },
]
}

下面是我的代码。

# Snippet Model
from django.db import models
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey('auth.User', related_name='snippets')

# Snippet serializer
class SnippetSerializer(serializers.ModelSerializer):
model = Snippet
fields = ('id','created')

# User serializer
from .serializers import SnippetSerializer
class UserSerializer(serializers.ModelSerializer):
included = serializers.SerilizerMethodField()
class Meta:
model = User
depth = 1
fields = ('id','included')

def get_included(self, obj):
snippets = SnippetSerializer(many=True, read_only=True).data

return snippets

最佳答案

不需要 get_included 方法。只需将 snippets 属性添加到类中即可。

class UserSerializer(serializers.ModelSerializer):
included = SnippetSerializer(many=True, read_only=True)

class Meta:
model = User
depth = 1
fields = ('id','included')

关于python - Django Rest - 在 get_*** 方法中包含序列化器对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31124525/

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