我有两个模型Visit(父模型)和VisitAccessories(子模型)。当我发布(VisitAccessories)数据时,仅添加列表的最后一个元素并创建记录。但其他元素将被忽略。
models.py
class Visit(models.Model):
name = models.CharField(max_length=200, name="name")
class VisitAccessories(models.Model):
title = models.CharField(max_length=100)
code = models.CharField(max_length=100, null=True, blank=True)
accessories_photo = models.FileField(upload_to="accessories/", null=True, blank=True)
description = models.TextField(null=True, blank=True)
visit = models.ForeignKey(Visit,on_delete=models.CASCADE)
serializer.py
class VisitAccessoriesSerializers(serializers.ModelSerializer):
class Meta:
model = VisitAccessories
exclude = ("visit",)#visit is foregin key to visit model
class ListAccessoriesSerializers(serializers.ModelSerializer):
visit_accessories = VisitAccessoriesSerializers(many=True,source='visitaccessories_set', required=False,)
class Meta:
model = VisitAccessories
exclude = ("visit",) #visit is foregin key to visit model
class VisitSerializers(serializers.ModelSerializer):
visit_accessories = VisitAccessoriesSerializers(many=True, source='visitaccessories_set', required=False)
class Meta:
model = Visit
fields = ('__all__')
views.py
def post(self, request):
serializer = VisitSerializers(data=request.data)
accessories_serializer = ListAccessoriesSerializers(data=request.data)
if serializer.is_valid(raise_exception=ValueError) and accessories_serializer.is_valid(raise_exception=ValueError):
visit_obj = serializer.save() # Visit Created
accessories_serializer.save(visit=visit_obj) # VisitAccessories
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)
我得到的变量accessories_serializer
数据是
ListAccessoriesSerializers(data=<QueryDict: {'name': ['Axxx'], 'gender': ['M'], 'mobile': ['900000'], 'visit_time': ['2019-06-04T17:00:56.901634+05:30'], 'to_meet': ['15'], 'title': ['pppp', 'ttttttt', 'vvvvv'], 'accessories_photo': [<InMemoryUploadedFile: Syndicate_Bank.svg.png (image/png)>, <InMemoryUploadedFile: maruti-suzuki-reuters-small.jpg (image/jpeg)>, <InMemoryUploadedFile: rupee11.jpg (image/jpeg)>]}>):
仅从标题列表vvvvv
(最后一个元素)创建1条记录。而不是3条记录
答案 0 :(得分:0)
Try this
class VisitSerializers(serializers.ModelSerializer):
visit_accessories = VisitAccessoriesSerializers(many=True, source='visitaccessories_set', required=False)
class Meta:
model = Visit
fields = ('__all__')
def create(self, validated_data):
request = self.context.get('request')
accessories_data = validated_data.pop('visit_accessories') # pop the nested data
serializer = VisitSerializers(data=validated_data)
instance = super().create(validated_data) # create base object
accessories_serializer = ListAccessoriesSerializers(many=True,
context={'request': request, 'visit_id': instance.id}
)
accessories_serializer.create(accessories_data) # create nested objects
return instance