我的模型Manager
与User
有一个ForeignKey。
要更新发件人,我会发送PATCH
方法,其中包含{"user": {"first_name": "John", "last_name": "Doe", "email": "john@doe.com"}
class CompanyManagerMeSerializer(serializers.ModelSerializer):
user = UserMeSerializer()
company = CompanyFullSerializer()
def update(self, instance, validated_data):
user_data = validated_data.pop('user', {})
user = instance.user
for key, val in user_data.items():
setattr(user, key, val)
user.save()
company_data = validated_data.pop('company', {})
company = instance.company
for key, val in company_data.items():
setattr(company, key, val)
company.save()
for key, val in validated_data.items():
setattr(instance, key, val)
instance.save()
return instance
class Meta:
model = CompanyManager
fields = ("pk", "user", "company", "display_name")
read_only_fields = ("display_name",)
在email
的{{1}}字段中添加验证器之前,这一切都正常工作:
UserMeSerializer
现在验证将失败,因为UserMeSerializer没有获得class UserMeSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
validators=[UniqueValidator(
queryset=User.objects.all(),
message=_("This email address is already used.")
)]
)
class Meta:
model = User
fields = (
'pk', 'first_name', 'last_name', 'username', 'email', 'date_joined', 'last_login'
)
read_only_fields = ('pk', 'date_joined', 'last_login')
参数,因此唯一检查不知道它找到的电子邮件地址是我们正在检查的地址...... see the source of UniqueValidator
所以我的问题是:如何告诉instance
我正在UserMeSerializer
实例上工作?我应该覆盖companymanager.user
吗?
答案 0 :(得分:-1)
我相信编写一个扩展UniqueValidator
的自定义验证器会有所帮助。
您可以检查上下文并相应地设置self.instance
。为此,您必须实施set_context()方法。