如何创建从用户继承的测试用户

How To Create A Test User Which Inherits From User

我有以下用户类型:

class User(AbstractUser):
    user_type = models.CharField(choices=USER_TYPES, max_length=255, default='student')

class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

为功能测试 id 创建用户时通常这样做:

user = get_user_model().objects.create_user(username='test', email='test@example.com', password='passwordtest')
EmailAddress.objects.create(user=user, email="example@example.com", primary=True, verified=True)

对于此测试,我需要创建一个学生,但找不到有关如何执行此操作的任何信息。我尝试的一切,例如:

user = get_user_model().objects.create_user(username='test', email='test@example.com', password='passwordtest')
user = Student.objects.create(user=user)

导致这样的错误:

django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'user_id'")

谢谢。

django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'user_id'")

这意味着您的数据库已经包含一个学生,该学生与您的用户 user.id as 1(可能是用户名“test”)

您只需拨打:

student = Student.objects.filter(user__username="test")
print(student)

或使用 get_or_create 作为:

student = Student.objects.get_or_create(user__id=1)
print(student)

或删除您的数据库并重新开始,然后调用此:

user = get_user_model().objects.create_user(username='test', email='test@example.com', password='passwordtest')
user = Student.objects.create(user=user)