仅当两个对象都有效时,才保存多个对象
我有多个来自请求的序列化对象作为JSON文件。我只想在数据库中存储它们是有效的(所有这些都必须有效)。
默认情况下,django保存TripSerializer
。然后,如果在imageserializer
中出现错误,则将TripSerializer
保留在数据库中。
那么,只有在两者有效的情况下才能保存它们呢?
def post_images(trip_id,data):
data['trip']=trip_id
imageserializer = TripImageSerializer(data = data)
if serializer.is_valid():
imageserializer.save()
return Response(status = status.HTTP_201_CREATED)
return Response({'images':imageserializer.errors},status= status.HTTP_400_BAD_REQUEST)
class Trip_apiView(generics.ListCreateAPIView):
queryset= Trip.objects.all()
serializer_class=TripSerializer
def post(self, request):
data = request.data
dataImg=data.pop('trip_images')
if tripserializer.is_valid():
instance = tripserializer.save()
respo=post_images(instance.pk,dataImg)
if respo.status_code==400: return respo
return Response(tripserializer.errors, status= status.HTTP_400_BAD_REQUEST)
这是JSON:
{
"id": 137,
"trip_images": [
{"image_title":"image1","image_order":1},
{"image_title":"image2","image_order":2}
],
"title": "dqw",
"description": "nice",
"start_date": "2022-02-08T12:00:00Z",
"end_date": "2022-02-14T12:00:00Z",
}
I have multiple serializers objects that comes from the request as json file. I want to store them inside databases only if they are Valid (all of them must be VALID).
by default DJANGO save tripserializer
. then if error occors in imageserializer
,it keep tripserializer
in database.
so how can save them only if they are valid both of them?
def post_images(trip_id,data):
data['trip']=trip_id
imageserializer = TripImageSerializer(data = data)
if serializer.is_valid():
imageserializer.save()
return Response(status = status.HTTP_201_CREATED)
return Response({'images':imageserializer.errors},status= status.HTTP_400_BAD_REQUEST)
class Trip_apiView(generics.ListCreateAPIView):
queryset= Trip.objects.all()
serializer_class=TripSerializer
def post(self, request):
data = request.data
dataImg=data.pop('trip_images')
if tripserializer.is_valid():
instance = tripserializer.save()
respo=post_images(instance.pk,dataImg)
if respo.status_code==400: return respo
return Response(tripserializer.errors, status= status.HTTP_400_BAD_REQUEST)
this is JSON :
{
"id": 137,
"trip_images": [
{"image_title":"image1","image_order":1},
{"image_title":"image2","image_order":2}
],
"title": "dqw",
"description": "nice",
"start_date": "2022-02-08T12:00:00Z",
"end_date": "2022-02-14T12:00:00Z",
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要为整个JSON数据运行验证,可以将
tripimageserializer
用作trip_images
tripserializer
的字段的序列化器:因此您要做:
is_valid()
WIL,然后还运行trip_images
的验证。If you want the validation to run for the whole json data, you can use
TripImageSerializer
as the serializer for thetrip_images
field ofTripSerializer
:so if you do:
is_valid()
wil then run the validations fortrip_images
as well.