gpt4 book ai didi

python - Django REST框架: nested serializer not properly validating data

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:02 25 4
gpt4 key购买 nike

我是 DRF(和 Django)的新手,并尝试创建一个能够验证以下请求数据的嵌套序列化器:

{
"code": "12345",
"city": {
"name": "atlanta",
"state": "Georgia"
},
"subregion": {
"name": "otp north"
}
}

为了简化客户端的工作,我希望这个单个请求在数据库中创建多个记录:

  • 城市(如果尚不存在匹配的城市)
  • 子区域(如果尚不存在匹配的子区域)
  • 引用城市和(可选)子区域的 CodeLog

型号:

class City(models.Model):
name = models.CharField(max_length=75, unique=True)
state = models.CharField(max_length=50, blank=True)

class Subregion(models.Model):
city = models.ForeignKey(City)
name = models.CharField(max_length=75)

class CodeLog(models.Model):
code = models.CharField(max_length=10)
city = models.ForeignKey(City)
subregion = models.ForeignKey(Subregion, blank=True, null=True)

序列化器:

class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
fields = ('name', 'state')

class SubregionSerializer(serializers.ModelSerializer):
class Meta:
model = Subregion
fields = ('name',)

class CodeLogSerializer(serializers.ModelSerializer):
city = CitySerializer()
subregion = SubregionSerializer(required=False)

class Meta:
model = CodeLog
fields = ('code', 'city', 'subregion')

# This is where I'm having troubles
def create(self, validated_data):
city_data = validated_data.pop('city', None)
subregion_data = validated_data.pop('subregion', None)
if city_data:
city = City.objects.get_or_create(**city_data)[0]
subregion = None
if subregion_data:
subregion = Subregion.objects.get_or_create(**subregion_data)[0]

code_log = CodeLog(
code=validated_data.get('code'),
city=city,
subregion=subregion
)
code_log.save()
return code_log

查看:

class CodeLogList(APIView):
serializer_class = CodeLogSerializer

def post(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我能够让它与平面请求结构一起工作,嵌套序列化器被证明很难掌握。我是否走在正确的轨道上,或者是否有更理想的结构可以更好地工作?非常感谢任何帮助!

最佳答案

您的 Subregion 模型有一个 city 字段,该字段是外键且不能为空。您的 create 方法应该像这样。

def create(self, validated_data):
city_data = validated_data.pop('city', None)
subregion_data = validated_data.pop('subregion', None)
if city_data:
city = City.objects.get_or_create(**city_data)[0]
subregion = None
if subregion_data:
# Add city in Subregion data
subregion_data.update({'city': city})
subregion = Subregion.objects.get_or_create(**subregion_data)[0]

code_log = CodeLog(
code=validated_data.get('code'),
city=city,
subregion=subregion
)
code_log.save()
return code_log

关于python - Django REST框架: nested serializer not properly validating data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48492639/

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