我正在使用Django REST框架。我想将数据与父模型一起添加到子模型。基本上一次创建两个记录。
models.py
class Visit(models.Model):
name = models.CharField(max_length=200)
gender = models.CharField(choices=GENDER_CHOICE, max_length=1)
mobile = models.CharField(max_length=18,default="")
email = models.CharField(max_length=256, null=True, blank=True)
address = models.TextField(null=True, blank=True)
visit_type = models.IntegerField(choices=VISIT_TYPE)
visit_purpose = models.CharField(max_length=250)
visitor_photo = models.FileField(upload_to="visitor/",null=True, blank=True)
id_photo = models.FileField(upload_to="id_card/",null=True, blank=True)
date_created = models.DateTimeField(default=timezone.now, editable=False)
class Status(models.Model):
visit = models.ForeignKey(Visit,on_delete=models.CASCADE)
description = models.CharField(max_length=200)
from_time = models.DateField()
to_time = models.DateTimeField(null=True, blank=True)
aproved = models.BooleanField(default=False)
visit_complete = models.BooleanField(default=False)
exit_time = models.DateTimeField(null=True, blank=True)
date_created = models.DateTimeField(default=timezone.now, editable=False)
serializers.py
class StatusSerializers(serializers.ModelSerializer):
class Meta:
model = Status
fields = "__all__"
class VisitSerializers(serializers.ModelSerializer):
visit = StatusSerializers(many=True)
class Meta:
model = Visit
fields = "__all__"
def create(self, validated_data):
print(validated_data)
model_b = Visit.objects.create(**validated_data)
# print(self.context.request.data.get('description'))
child_model_data = {
'description': self.context.request.data.get('description'),
}
child_model_serializer = StatusSerializers(data=child_model_data)
child_model_serializer.is_valid(raise_exception=True)
child_model_serializer.save(status=model_b)
return model_b
views.py
@api_view(['GET', 'POST'])
def create_visitor(request):
if request.method == 'GET':
visitor = Visit.objects.all()
serializer = VisitSerializers(visitor,context={'request': request},many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = VisitSerializers(data=request.data,context={'request': request})
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) 在上面的代码中,我能够创建子记录,即状态模型记录,但是我不知道如何在创建过程中向其添加其他字段。
答案 0 :(得分:2)
在serializer
的子模型中,数据可以在self.context.request.data
中找到,您可以简单地使用子序列化程序来验证并保存在db中。
class VisitSerializers(serializers.ModelSerializer):
class Meta:
model = Visit
fields = "__all__"
def create(self, validated_data):
print(validated_data)
model_b = Visit.objects.create(**validated_data)
child_model_data = {
'field': self.context['request'].data.get('your_field');
.....
}
child_model_serializer = ChildSerializer(data=child_model_data)
child_model_serializer.is_valid(raise_exception=True)
child_model_serializer.save()
return model_b
首先,在视图后序列化器初始化中,您需要传递上下文对象。
@api_view(['GET', 'POST'])
def create_visitor(request):
if request.method == 'GET':
visitor = Visit.objects.all()
serializer = VisitSerializers(visitor,context={'request': request},many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = VisitSerializers(data=request.data, context={'request': request})
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)
然后在您的VisitSerializer中
class VisitSerializers(serializers.ModelSerializer):
visit = StatusSerializers(many=True) # not sure why you did this, this should be removed i guess
class Meta:
model = Visit
fields = "__all__"
def create(self, validated_data):
print(validated_data)
model_b = Visit.objects.create(**validated_data)
# print(self.context.request.data.get('description'))
child_model_data = {
'description': self.context.request.data.get('description'),
'status': model_b
# and make sure all other necessary fields.
}
child_model_serializer = StatusSerializers(data=child_model_data)
child_model_serializer.is_valid(raise_exception=True)
child_model_serializer.save()
return model_b
答案 1 :(得分:0)
您可以在序列化器中包含其他字段以及默认字段。对于反向关系,您可以添加这样的字段
class VisitSerializers(serializers.ModelSerializer):
status = StatusSerializer(many=True)
class Meta:
model = Visit
您可以像这样将数据传递给VisitSerializer。 {,状态:[,]}