我有两个型号CustomUser和UserProfile。
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254, unique=True, blank=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
class UserProfile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
owner_of = models.CharField(max_length=100, blank=True)
total_years= models.CharField(_('In Current Profession Since'),max_length=100,blank=True, null=True)
serializers.py:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = ('id', 'email','first_name', 'last_name',)
class ProfileSerializer(serializers.ModelSerializer):
user = AccountSerializer(read_only=True,required=False)
class Meta:
model = UserProfile
fields = ('user','owner_of','total_years','first_name','last_name','email')
我得到的错误
"字段名first_name
对模型UserProfile
无效。"
如何组合两个模型字段并创建和更新功能
答案 0 :(得分:2)
您的个人资料订阅者应该是这样的,
class ProfileSerializer(serializers.ModelSerializer):
user = AccountSerializer(required=True)
class Meta:
model = UserProfile
fields=('user','owner_of','total_years')
结果如下,
{
{
"user":
{
"id: ...,
"first_name": ...,
"last_name": ...,
"email": ...
},
"owner_of": ...,
"total_years" ...
},
...
}
More detailed explanation is here
默认情况下,嵌套序列化程序是只读的。如果要支持对嵌套序列化程序字段的写操作,则需要创建create()和/或update()方法,以便明确指定应如何保存子关系。
class ProfileSerializer(serializers.ModelSerializer):
user = AccountSerializer(required=True)
class Meta:
model = UserProfile
fields=('user','owner_of','total_years')
def create(self, validated_data):
user_data = validated_data.pop('user')
user= CustomUser.objects.create(**user_data)
user_profile=UserProfile.objects.create(user=user, **validated_data)
return user_profile
def update(self, instance, validated_data):
user_data = validated_data.pop('user', None)
user = instance.user
instance.owner_of = validated_data.get("owner_of", instance.owner_of)
instance.total_years= validated_data.get("total_years", instance.total_years)
instance.save()
if user_data:
user.first_name = user_data.get("first_name", user.first_name)
user.last_name = user_data.get("last_name", user.last_name)
user.email= user_data.get("email", user.email)
user.save()