如何在DRF中序列化相关对象。我有三个模型auth_user(User),ModelA,ModelB。
我的模特:
class ModelA(models.Model):
user = models.OneToOneField(auth_user, related_name = 'modelA')
name = models.CharField(max_length = 30)
class ModelB(models.Model):
owner = models.OneToOneField(auth_user)
user = models.OneToOneField(auth_user, related_name = 'modelB')
type = models.ForeignKey(ModelD)
cost = models.IntegerField()
class ModelD(models.Model):
type_desc = models.CharField(max_length = 40)
我的序列化器:
class A(serializers.ModelSerializer):
class Meta:
model = ModelA
fields = ('name', )
class B(serializers.ModelSerializer):
class Meta:
model = ModelB
fields = ('type', 'cost', )
class AuthUserSerilaizer(serializers.ModelSerializer):
userA = serializers.RelatedField(source = 'modelA')
userB = serializers.RelatedField(source = 'modelB')
class Meta:
model = User
fields = ('email', 'password', 'userA', 'userB', )
write_only_fields = ('password',)
@transaction.commit_manually
def restore_object(self, attrs, instance = None):
try:
user = User.objects.create_user(email = attrs.get('email'), password = attrs.get('password'))
modela = ModelA(user =user, name = attrs.get('name'))
modela.save()
transaction.commit()
return User(email = attrs.get('email'))
except Exception ,e:
transaction.rollback()
print repr(e)
JSON我传递
data = {'email':'123@gmail.com,
'password' : 'dummy',
'userA' : {'name' :'123'},
'userB':{'type':1,'cost':'100'}
无论什么时候发出POST请求,都可以使用' attrs'只获得电子邮件和密码而不是userA和userB,为什么?如何在相应的表中串行反序列化和创建数据。
答案 0 :(得分:1)
在您的视图中尝试此操作
from django.core.serializers.json import DjangoJSONEncoder
import json
response = json.dumps(data,cls=DjangoJSONEncoder)
return HttpResponse(response, mimetype="application/json")
并且在成功功能中,您可以使用
进行访问usera_name = response.userA.name
userb_type = response.userB.type
userb_cost = response.userB.cost