self.create()存储与父模型分离的数据

时间:2019-04-08 20:10:19

标签: django django-models django-rest-framework django-views

我的问题是我的UserProfileModel具有嵌套的SubscriptionModel,当我调用self.create()方法时,它会将SubscriptionModel存储在父模型“ UserProfileModel”之外。

该脚本也完美地将用户存储在User模型和UserProfileModel中,没有麻烦,但是当涉及SubscriptionModel时,脚本将其存储,但不存储在永久模型“ UserProfileModel”中。

class SubscriptionModel(models.Model):

    subscription_name = models.CharField(_('subscription name'), max_length=50, choices=SUBSCRIPTION, default='F')

    def __str__(self):
        return self.subscription_name

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

# The parent model.

class UserProfileModel(models.Model):


    user = models.OneToOneField(User, on_delete=models.CASCADE, default='', related_name='user_instance')
    subscription = models.OneToOneField(SubscriptionModel, related_name='user_subscription', on_delete=models.CASCADE, blank=True, null=True)

    # Other fields....

    objects = UserProfileManager()

# The UserProfileManager() functions.

 @transaction.atomic
    def create_user_profile(self, user, subscription):
        password = user.pop('password')
        user = User(**user)
        user.set_password(password)
        user.save()
        subscription = SubscriptionModel(**subscription).save()
        self.create(user=user, subscription=subscription)
        return user

# The UserRegistrationSerializer.

class UserRegistrationSerializer(serializers.Serializer):

    subscription_name = serializers.ChoiceField(choices=SubscriptionModel.SUBSCRIPTION, default='F')

   # Other fields...

    def get_cleaned_data(self):
        return {
            'username': self.validated_data.get('username', None),
            'first_name': self.validated_data.get('first_name', None),
            'last_name': self.validated_data.get('last_name', None),
            'email': self.validated_data.get('email', None),
            'password': self.validated_data.get('password', None)
        }

   def get_subscription_cleaned_data(self):
        return {
            'subscription_name': self.validated_data.get('subscription_name', None)
        }

    def save(self, request):
        print(request.data)
        cleaned_data = self.get_cleaned_data()
        subscription = self.get_subscription_cleaned_data()
        user = UserProfileModel.objects.create_user_profile(user=cleaned_data, subscription=subscription)
        return user

0 个答案:

没有答案