重写save()方法

2024-10-03 00:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django中有一个自定义用户模式,用于处理角色或用户类型,创建一个名为userprofile的应用程序,该应用程序将设置或将设置我的自定义用户模型。在

在我的设置.py我有以下配置:

INSTALLED_APPS = [
        ...
    'userprofile',
]
#Custom model Users
AUTH_USER_MODEL = 'userprofile.User'

我自定义我的用户类(userprofile/模型.py)继承AbstractUser类以根据我的需求向我的用户模型添加一些字段。在

我还为角色/概要文件用户(MedicalProfile, PatientProfile, PhysiotherapistProfile)创建了这些具有自己字段或属性的模型

另外,MedicalProfile, PatientProfile, PhysiotherapistProfile与我的自定义模型/类User有一个单字段关系,因此:

^{pr2}$

我的问题

我想把我的问题集中在重写过程save()方法上:

def save(self, *args, **kwargs):
    if self.is_medical:
        profile = MedicalProfile(user=self)
        super(User, self).save(self, *args, **kwargs)
        profile.save()

我想,每个创建用户的用户,自动创建他们的配置文件(MedicalProfile,PatientProfile,Physical TherapistProfile),如果他们的字段被选中(is_medical,is_patient,is_Physical治疗师)

我的不方便之处在于我的覆盖过程如下:

  • 当我通过django admin创建一个用户时,我得到了这个错误

enter image description here

我不知道,关于原因是什么设置用户PK为无。。。在

我可以有什么替代方案来解决这种情况,当我创建一个用户时,根据我选择的属性checkbo/field(is_medical,is_physical therapist,is_patient),保存他们的配置文件实例(MedicalProfile,physical theraprofile,PatientProfile)?在

如果我的问题不符合stackoverflow的哲学或我的问题的范围,我在此之前向您致歉。在

是因为我想把所有的细节都告诉我,以便得到答案

任何介绍我都会很感激和感激的


Tags: 用户py模型self应用程序角色属性is
2条回答

如果用户不是医务人员,则需要在save方法中执行一些操作;您仍然需要实际保存对象。在

固定的实施方式是:

def save(self, *args, **kwargs):
    user = super(User, self).save(self, *args, **kwargs)
    if self.is_medical:
        MedicalProfile(user=self).save()

位于userprofile/models.py中的我的class User正在重写save方法,保持不变:

class User(AbstractUser):
    is_medical = models.BooleanField(default=False)
    is_physiotherapist = models.BooleanField(default=False)
    is_patient = models.BooleanField(default=False)
    slug = models.SlugField(max_length=100, blank=True)
    photo = models.ImageField(upload_to='avatars', null = True, blank = True)

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

        # Creating and user with medical, patient and physiotherapist profiles
        if self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\
                and self.is_patient and not PatientProfile.objects.filter(user=self).exists()\
                and self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists():

            medical_profile=MedicalProfile(user=self).save()
            patient_profile=PatientProfile(user=self).save()
            physiotherapist_profile=PhysiotherapistProfile(user=self).save()
            #profile.save()

        # Creating and user with medical and patient profiles
        elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\
            and self.is_patient and not PatientProfile.objects.filter(user=self).exists():

            medical_profile=MedicalProfile(user=self).save()
            patient_profile=PatientProfile(user=self).save()

        # Creating and user with medical and physiotherapist profiles
        elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists()\
            and self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists():

            medical_profile=MedicalProfile(user=self).save()
            physiotherapist_profile=PhysiotherapistProfile(user=self).save()

        # Creating and user with physiotherapist and patient profiles
        elif self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists()\
            and self.is_patient and not PatientProfile.objects.filter(user=self).exists():

            physiotherapist_profile = PhysiotherapistProfile(user=self).save()
            patient_profile = PatientProfile(user=self).save()

        # Creating and user with medical profile
        elif self.is_medical and not MedicalProfile.objects.filter(user=self).exists():
            profile = MedicalProfile(user=self)
            profile.save()

        # Creating and user with patient profile
        elif self.is_patient and not PatientProfile.objects.filter(user=self).exists():
            profile = PatientProfile(user=self)
            profile.save()

        # Creating and user with physiotherapist profiles
        elif self.is_physiotherapist and not PhysiotherapistProfile.objects.filter(user=self).exists():
            profile = PhysiotherapistProfile(user=self)
            profile.save()



    # We get the profiles user according with their type
    def get_medical_profile(self):
        medical_profile = None
        if hasattr(self, 'medicalprofile'):
            medical_profile=self.medicalprofile
        return medical_profile

    def get_patient_profile(self):
        patient_profile = None
        if hasattr(self, 'patientprofile'):
            patient_profile = self.patientprofile
        return patient_profile

    def get_physiotherapist_profile(self):
        physiotherapist_profile = None
        if hasattr(self, 'physiotherapistprofile'):
            physiotherapist_profile = self.physiotherapistprofile
        return physiotherapist_profile

    # We redefine the attributes (create db_table attribute) in class Meta to say to Django
    # that users will save in the same table that the Django default user model
    # https://github.com/django/django/blob/master/django/contrib/auth/models.py#L343
    class Meta:

        db_table = 'auth_user'

class MedicalProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    #active = models.BooleanField(default=True)
    name = models.CharField(max_length=64)


class PatientProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    #active = models.BooleanField(default=True)
    name = models.CharField(max_length=64)


class PhysiotherapistProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    #active = models.BooleanField(default=True)
    name = models.CharField(max_length=64)

# Enter the username as slug field
@receiver(post_save, sender = settings.AUTH_USER_MODEL)
def post_save_user(sender, instance, **kwargs):
    slug = slugify(instance.username)
    User.objects.filter(pk=instance.pk).update(slug=slug)

save()方法让我用所有可能的配置文件组合保存用户。在

但是,有更好的方法吗?在

相关问题 更多 >