如何解决成功地从引用模型转换为子类需要什么?
我当前正在使用两个请求来创建用户和医生(或患者)。我想在一个请求中执行此操作,以便以后确定用户类型也更加容易。
这就是我扩展用户的条件
# models
class User(AbstractUser):
ROLES = (
('d','Doctor'),('s','Secretary'),('p','Patient'),)
role = models.CharField(
max_length=1,choices=ROLES,blank=True,default='p',help_text='Role')
class Doctor(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
clinic = models.ManyToManyField(
Clinic,related_name="doctors",blank=True)
appointment_duration = models.IntegerField(default=20,blank=True)
# serializer
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','username','password','role','first_name','last_name','email','phone')
extra_kwargs = {'password': {'write_only': True,'required': True}
# viewset
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (AllowAny,)
这是我尝试过的:
class User(AbstractUser):
pass
class Doctor(User):
clinic = models.ManyToManyField(
Clinic,blank=True)
首先,在从user
删除Doctor
字段之前,终端中存在此错误
clinic.Doctor.user: (fields.E305) Reverse query name for 'Doctor.user' clashes with reverse query name for 'Doctor.user_ptr'.
HINT: Add or change a related_name argument to the definition for 'Doctor.user' or 'Doctor.user_ptr'.
然后我删除了Doctor的user
属性,错误消失了,但是现在当我尝试迁移时,显示如下:
You are trying to add a non-nullable field 'user_ptr' to doctor without a default; we can't do that (the database needs something to populate existing rows).
ps。我还打算能够使用电子邮件而不是用户名进行注册/登录;如果能影响到这一点,我将不胜感激。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。