簡體   English   中英

如何使用 Django 中的 Abstractuser 類創建兩個不同的用戶(醫生和患者),以便他們都可以發揮自己的作用

[英]How to create two different users(doctor and patient) using Abstractuser class in Django so that both of them can perform their own role

我想用這些詳細信息創建兩個用戶。

class Doctor(models.Model):
    username = models.CharField(max_length=500)
    password = models.CharField(max_length=500, null=True)
    gender = models.CharField(choices=GENDER_CHOICES, max_length=128)
    specialties = models.CharField(max_length=1000)
    education = models.CharField(max_length=1000)
    hospitals = models.CharField(max_length=1000)
    rate = models.FloatField()
    email = models.EmailField(unique=True)
    description = models.TextField(null=True)
class Patient(models.Model):
    username = models.CharField(max_length=500)
    password = models.CharField(max_length=500, null=True)
    email = models.EmailField(unique=True)
    gender = models.CharField(choices=GENDER_CHOICES, max_length=128)
    age = models.IntegerField()
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)

我也開始使用這種方法,並且根據您的問題出現的時間來判斷,您很可能已經弄清楚了這一點,但是我想回答這個問題,因為不久前我還在尋找答案,並且也許這可以幫助其他人。

無論如何,我以前在這個 AbstractUser 之前使用過“類似個人資料”的方式,但是在您的回答中,我看到它們是混合的,在您的患者模型中,您將 OneToOne FK 用於原始 auth_user 模型,但是您要求抽象用戶。 因此,以防萬一您正在尋找真正稱為“代理模型”選項的“Profile like”,您已經快完成了,您只需要像在患者模型中一樣向用戶添加一個 OneToOne 字段,但在Doctor 模型,然后您將有兩個帶有額外信息的模型,但與登錄、訪問或權限無關,僅用於個人資料,准備就緒。 以下鏈接上的文檔解釋了此代理模型基本文檔

現在,如果您正在尋找的是使用另一種方式,替換用戶模型,您需要 AbstractUser,您需要做什么(或者更好地說明,您可以做什么,這就是我現在正在做的) ) 是創建一個基本的自定義用戶類。 你可以在文檔中看到一個完整的例子在你的情況下

class MyBaseUser(AbstractUser):
    username = models.CharField(max_length=500)
    password = models.CharField(max_length=500, null=True)
    email = models.EmailField(unique=True)
    gender = models.CharField(choices=GENDER_CHOICES, max_length=128)


class Doctor(MyBaseUser):
    max_length=128)
    specialties = models.CharField(max_length=1000)
    education = models.CharField(max_length=1000)
    hospitals = models.CharField(max_length=1000)
    rate = models.FloatField()
    description = models.TextField(null=True)

class Patient(MyBaseUser):
    age = models.IntegerField()

現在,請記住,您需要在設置中指定 AUTH_USER_MODEL,您可以遵循 cookiecutter 模板,因此所有這些都將被預先格式化。 此外,您可以在 MyBaseUser 類中添加 USERNAME_FIELD 以說明哪個字段將用作登錄用戶名,以及同一類中的 REQUIRED_FIELDS。

正如我們的朋友德斯汀喜歡說的那樣,祝您愉快。

暫無
暫無

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

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