簡體   English   中英

獲取用戶 model 數據並更新 django 中的另一個 model

[英]Fetch user model data and update another model in django

我有用戶 model 使用 AbstractBaseUser class。 我正在使用 email、用戶名和密碼注冊用戶。 用戶 class:

class User(AbstractBaseUser):
    """
    Creates a customized database table for user
    """
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    username = models.CharField(max_length=255, unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email',]

    objects = UserManager()

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

我想將此 model 擴展到另一個名為 Employee 的 model。 為了將用戶 model 擴展到員工 model,我使用了 django 信號 ZA2F2ED4F8EBC2CBB4C21A29DC40AB61D 員工 class:

class Employee(models.Model):
    """
    Create employee attributes
    """
    employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True)
    e_id = models.IntegerField(unique=True, null=True, blank=True)
    first_name = models.CharField(max_length=128,blank=True)
    last_name = models.CharField(max_length=128, blank=True)
    address = models.CharField(max_length=256, blank=True)
    phone_number = models.CharField(max_length=128, blank=True)
    email = models.EmailField(max_length=128, unique=True)
    
    @receiver(post_save, sender=User)
    def create_or_update_user_profile(sender, instance, created, **kwargs):
        if created:
            Employee.objects.create(employee_user=instance)
        instance.Employee.save()

在這個 model 中還有一個名為 email 的字段。 我必須保留此字段,因為我正在使用此 model 創建員工創建表單。 但問題是,用戶模型的 email 字段與員工 email 字段沖突。 我必須保留兩個 email 字段。

我可以用用戶 email 字段更新員工 email 字段嗎? 如果是,那么應該查詢什么???

您可以執行Employee.objects.create(employee_user=instance, email=instance.email) ,但您應該評估是否需要在兩個表中重復數據。 只要您有 Employee 實例,您就可以隨時訪問employee.employee_user.email

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM