I have the following User types:
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)
When creating a User for a functional test id usually do this:
user = get_user_model().objects.create_user(username='test', email='[email protected]', password='passwordtest')
EmailAddress.objects.create(user=user, email="[email protected]", primary=True, verified=True)
For this test I need to create a Student, yet cant find any information on how to do this. Everything I try, such as this:
user = get_user_model().objects.create_user(username='test', email='[email protected]', password='passwordtest')
user = Student.objects.create(user=user)
Results in errors such as this:
django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'user_id'")
Thank you.
django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'user_id'")
What this means is that your database already contains a student attached to your user with user.id as 1
(probably with username "test")
You can simply call:
student = Student.objects.filter(user__username="test")
print(student)
or use get_or_create
as:
student = Student.objects.get_or_create(user__id=1)
print(student)
or delete your database and start fresh then call this:
user = get_user_model().objects.create_user(username='test', email='[email protected]', password='passwordtest')
user = Student.objects.create(user=user)