在我的项目中,我有两种“类型”的用户:客户和企业。它们是django.contrib.auth.models.User
中django基本用户的扩展。
我在models.py
中:
class Customer(models.Model):
user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE)
birth_date = models.DateField(blank=True, null=True)
phone = PhoneNumberField(unique=True)
def __str__(self):
return self.user.username
class Business(models.Model):
user = models.OneToOneField(User, related_name='business', on_delete=models.CASCADE)
cf = models.CharField(max_length=16, validators=[ssn_validation])
birth_date = models.DateField(null=True)
city = models.CharField(max_length=50, blank=False)
address = models.CharField(max_length=150, blank=False)
好,那么我有两种不同的注册方式,一种针对客户,一种针对企业。一个问题是,要验证从REST API发送的密码,我需要将password
与password2
进行比较,创建一个User(django base),然后将其传递给我的Customer.objects.create,例如:] >
我在serializers.py
中:
class CustomerRegistationSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username', validators=[UniqueValidator(queryset=User.objects.all())]) email = serializers.CharField(source='user.email', validators=[UniqueValidator(queryset=User.objects.all())]) first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') password = serializers.CharField(source='user.password', write_only=True) password2 = serializers.CharField(style={'input_style': 'password'}, write_only=True) birth_date = serializers.CharField(required=False) class Meta: model = Customer fields = ['id', 'username', 'email', 'password', 'password2', 'first_name', 'last_name', 'birth_date', 'phone'] def save(self): username = self.validated_data['user']['username'] password = self.validated_data['user']['password'] password2 = self.validated_data['password2'] email = self.validated_data['user']['email'] first_name = self.validated_data['user']['first_name'] last_name = self.validated_data['user']['last_name'] phone = self.validated_data['phone'] try: birth_date = self.validated_data['birth_date'] except KeyError: birth_date = None if password != password2: raise serializers.ValidationError({'password': 'Passwords must match!'}) user = User.objects.create(username=username, email=email, first_name=first_name, last_name=last_name) user.set_password(password) user.is_active = False user.save() customer = Customer.objects.create(user=user, birth_date=birth_date, phone=phone) return customer
这实际上是有效的,但是如果发生错误,则可能会创建用户,而不会创建客户。有没有更清洁的方法来进行客户注册,总是检查
password == password2
?
在我的项目中,我有两种“类型”的用户:客户和企业。它们是django.contrib.auth.models.User的django基本用户的扩展。我在我的models.py中:class Customer(models ....
如果要要求您在save()
方法期间进行的所有数据库事务都能成功地将其有效地写入数据库,并且在过程中的任何时候都没有错误,则不要写入任何内容,通常要求atomicity