如何在ModelSerializer的create方法中实现update_or_create [英] How to implement update_or_create inside create method of ModelSerializer
问题描述
代码:
class OTP(AppModel):
phone_regex = RegexValidator(regex=r'^[6789]\d{9}$', message="phone no. is invalid.")
phone_number = models.CharField(validators=[phone_regex], max_length=10, unique=True)
code = models.CharField(max_length=255)
def __str__(self):
return str(self.phone_number) + ": "+str(self.code)
class OTPSerializer(serializers.ModelSerializer):
code = serializers.CharField(max_length=None, required=False)
class Meta:
model = OTP
fields = ('id', 'code', 'phone_number')
read_only_fields=('id', 'code')
@transaction.atomic
def create(self, validated_data):
phone_number = validated_data.pop("phone_number")
otp, created = OTP.objects.update_or_create(
phone_number=phone_number, defaults={"code": generate_otp()})
return otp
我正在尝试在 django-的
的 create
方法内执行 update_or_create
其余框架 ModelSerializer
。
I am trying to do update_or_create
inside the create
method of the django-rest-framework
's ModelSerializer
.
但是,字段<$ c $模型 OTP
中的c> phone_number 必须为唯一
。因此, unique = True
。
But, the field phone_number
inside the model OTP
must be unique
. Hence the unique=True
.
我能够发布电话号码
并创建对象。但是,再次发布相同的 phone_number
会引发错误 otp并且该电话号码已经存在
,而不是对其进行更新(如果已存在)存在,因为我已经覆盖了 create
方法。
I was able to post a phone_number
and create the object. But, posting the same phone_number
again throws error otp with this phone number already exists
, instead of updating it if it already exists as I have overridden the create
method. Please help!
推荐答案
您可以使用信号以一种干净的方式进行。只需将您创建的创建的
变量发送到您定义的接收器
,然后根据您的对象进行处理是否创建。对于REST响应,只需在序列化程序中覆盖 create
方法即可根据您所处的状态返回数据,或者 get您在APIView中使用的/ post / patch
方法不返回 serializer.data
,而是返回您想要的任何内容。
以下是信号接收器的示例:
You can use Signals to do this in a clean way. Simply, you can send a created
variable to a receiver
which you define, and deal with it based on either your object was created or not. in the case of the REST response, just override the create
method in the Serializer to return data based on the state you're in, or the get/post/patch
method you're using in the APIView to not return serializer.data
, and instead return whatever you want it to.
Here is an example for a signal receiver:
@receiver(post_save, sender=settings.OTP_MODEL)
def update(sender, instance=None, created=False, **kwargs):
if created:
# Do Something
else:
# Do Some Other thing
这篇关于如何在ModelSerializer的create方法中实现update_or_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!