gpt4 book ai didi

django - 列表序列化器多个对象创建

转载 作者:行者123 更新时间:2023-12-01 23:28:00 27 4
gpt4 key购买 nike

我的模型是:

class User(models.Model):
id = models.AutoField(primary_key=True)
email = models.EmailField()


class Lawyer(models.Model):
user = models.OnetoOneField(User)


class Session(models.Model):
name = models.CharField()
lawyer = models.ForeignKey(Lawyer)

我正在尝试使用 session 列表序列化器创建多个对象。
从应用程序方面来看,他们没有律师的ID,但有每个律师的电子邮件。如何编写一个列表序列化程序,在其中可以获取以下 json 输入并使用电子邮件获取律师来存储多个 session 对象?

发送的 json 输入将类似于:

[
{
"name": "sess1",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5c9c4d2dcc0d794e5c2c8c4ccc98bc6cac8" rel="noreferrer noopener nofollow">[email protected]</a>",
},
{
"name": "sess1",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7814190f011d0a49381f15191114561b1715" rel="noreferrer noopener nofollow">[email protected]</a>",
}
]

最佳答案

你可以用这种方式做到这一点,但我认为电子邮件应该是unique=True

然后使用像这样的序列化器:

from django.utils.translation import ugettext_lazy as _

class SessionCreateManySerializer(serializers.ModelSerializer):
email = serializers.SlugRelatedField(
source='lawyer',
slug_field='user__email',
queryset=Lawyer.objects.all(),
write_only=True,
error_messages={"does_not_exist": _('lawyer with email={value} does not exist.')}
)

class Meta:
model = Session
fields = ('name', 'email')

和通用创建 View (只需覆盖 get_serializer 并将 many=True 放入 kwargs 中):

from rest_framework.response import Response
from rest_framework import generics

class SessionCreateManyView(generics.CreateAPIView):
serializer_class = SessionCreateManySerializer

def get_serializer(self, *args, **kwargs):
kwargs['many'] = True
return super(SessionCreateManyView, self).get_serializer(*args, **kwargs)

关于django - 列表序列化器多个对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980395/

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