我想在表格中添加特定字段

时间:2019-04-27 15:31:10

标签: django

我有两个user_type学生和老师。 我想在更新个人资料时向教师和学生添加特定字段

class UserType(AbstractUser):
    user =models.OneToOneField(User, on_delete=models.CASCADE)
    USER_TYPE = (
        (1, 'Student'),
        (2, 'Teacher'),
    )
    user_type = models.IntegerField(choices=USER_TYPE)

在这里我创建了一个教师模型,可以在其中添加教师的额外字段

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user.user_type = 2
    specialty = models.CharField(max_length=20)
    picture = models.ImageField(upload_to = '', default = '')

    #return the teacher's name
    def __str__(self):
        return str(self.user)

类似地,我创建了一个Student模型来为用户添加额外的字段

class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user.user_type = 1        
    picture = models.ImageField(upload_to = '', default = '')


    #return the student's name
    def __str__(self):
        return str(self.user)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        if instance.user_type == 2:
            Teacher.objects.create(user=instance)
        elif instance.user_type == 1:
            Student.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    if instance.user_type == 2:
        instance.teacher.save()
    elif instance.user_type == "patient":
        instance.student.save()

我不知道如何添加用户类型特定的附加信息。我无法将教师和学生的实例另存为单独的表。而且个人资料也无效

0 个答案:

没有答案