使用 django-rest-framework 在 OneToOneField 上插入数据
Insert data on OneToOneField using django-rest-framework
我是这个 django-rest-framework 的新手,我的问题是如何在 views.py 中插入具有一对一关系的数据。
我可以像下面那样用正常的方式插入数据,
def post(self, request,format=None):
p = Person()
p.firstname = "John"
p.middlename = "K"
p.lastname = "Rambo"
p.save()
e = Employee()
e.code = "emp-002"
e.person_id = p.id
e.save()
我无法执行上述方法,因为我想了解有关 DRF 的更多信息。
为了给你更多的想法,请看下面:
我有这个型号
class Person(models.Model):
firstname = models.CharField(max_length=150, default="")
middlename = models.CharField(max_length=150, default="")
lastname = models.CharField(max_length=150, default="")
class Employee(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE,primary_key=True)
code = models.CharField(max_length=100, default="")
我有这个序列化器
class PersonSer(serializers.ModelSerializer):
class Meta:
model = Person
fields = (
'id',
'firstname',
'middlename',
'lastname',)
class EmployeeSer(serializers.ModelSerializer):
person = PersonSer()
class Meta:
model = Employee
fields = ('code','person')
我有这个看法
class SaveData(APIView):
@transaction.atomic
def post(self,request, format=None):
p = PersonSer(data=request.data)
if p.is_valid():
p.save()
request.data['person'] = p.data['id']
request.data['code'] = "Emp-"+str(p.data['id'])
"""
I expect request.data now equal to
{
'person' : 102, # we assume the newly created person id == 102
'code' : 'Emp-102',
'firstname' : 'John',
'middlename' : 'K.',
'lastname' : 'Rambo'
}
"""
es = EmployeeSer(data=request.data)
if es.is_valid():
es.save()
else:
print(es.errors) # {'person': [ErrorDetail(string='This field is required.', code='required')]}
"""
I also tried this,
es = EmployeeSer(data={'person' : p.data, 'code' : 'Sample code'})
if es.is_valid():
es.save()
else:
print(es.errors) #{'person': {'fullname': [ErrorDetail(string='This field may not be blank.',code='blank')], ]}}
"""
return Response({'message':'okay'})
request.data是一个formData,值为
{
'firstname' : 'John',
'middlename' : 'K.',
'lastname' : 'Rambo'
}
您可以覆盖 PersonSer 的创建方法来实现此目的。
class PersonSer(serializers.ModelSerializer):
...
def create(self, validated_data):
person = Person.objects.create(**validated_data)
Employee.objects.create(person=person, code=f"Emp-{person.id}")
return person
您可以将视图简化为:
...
@transaction.atomic
def post(self,request, format=None):
p = PersonSer(data=request.data)
p.is_valid(raise_exception=True)
p.save()
return Response({'message':'okay'})
...
如果存在验证错误,raise_expection=True
将导致序列化程序引发 ValidationError
异常。
我是这个 django-rest-framework 的新手,我的问题是如何在 views.py 中插入具有一对一关系的数据。 我可以像下面那样用正常的方式插入数据,
def post(self, request,format=None):
p = Person()
p.firstname = "John"
p.middlename = "K"
p.lastname = "Rambo"
p.save()
e = Employee()
e.code = "emp-002"
e.person_id = p.id
e.save()
我无法执行上述方法,因为我想了解有关 DRF 的更多信息。
为了给你更多的想法,请看下面:
我有这个型号
class Person(models.Model):
firstname = models.CharField(max_length=150, default="")
middlename = models.CharField(max_length=150, default="")
lastname = models.CharField(max_length=150, default="")
class Employee(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE,primary_key=True)
code = models.CharField(max_length=100, default="")
我有这个序列化器
class PersonSer(serializers.ModelSerializer):
class Meta:
model = Person
fields = (
'id',
'firstname',
'middlename',
'lastname',)
class EmployeeSer(serializers.ModelSerializer):
person = PersonSer()
class Meta:
model = Employee
fields = ('code','person')
我有这个看法
class SaveData(APIView):
@transaction.atomic
def post(self,request, format=None):
p = PersonSer(data=request.data)
if p.is_valid():
p.save()
request.data['person'] = p.data['id']
request.data['code'] = "Emp-"+str(p.data['id'])
"""
I expect request.data now equal to
{
'person' : 102, # we assume the newly created person id == 102
'code' : 'Emp-102',
'firstname' : 'John',
'middlename' : 'K.',
'lastname' : 'Rambo'
}
"""
es = EmployeeSer(data=request.data)
if es.is_valid():
es.save()
else:
print(es.errors) # {'person': [ErrorDetail(string='This field is required.', code='required')]}
"""
I also tried this,
es = EmployeeSer(data={'person' : p.data, 'code' : 'Sample code'})
if es.is_valid():
es.save()
else:
print(es.errors) #{'person': {'fullname': [ErrorDetail(string='This field may not be blank.',code='blank')], ]}}
"""
return Response({'message':'okay'})
request.data是一个formData,值为
{
'firstname' : 'John',
'middlename' : 'K.',
'lastname' : 'Rambo'
}
您可以覆盖 PersonSer 的创建方法来实现此目的。
class PersonSer(serializers.ModelSerializer):
...
def create(self, validated_data):
person = Person.objects.create(**validated_data)
Employee.objects.create(person=person, code=f"Emp-{person.id}")
return person
您可以将视图简化为:
...
@transaction.atomic
def post(self,request, format=None):
p = PersonSer(data=request.data)
p.is_valid(raise_exception=True)
p.save()
return Response({'message':'okay'})
...
如果存在验证错误,raise_expection=True
将导致序列化程序引发 ValidationError
异常。