I have this model in my Django application:
class ClubSession(models.Model):
location = models.CharField(max_length=200)
coach = models.ForeignKey('auth.User', on_delete=models.CASCADE)
date = models.DateTimeField(default=now)
details = models.TextField()
def __str__(self):
return self.location
This view implements it:
class SessionListView(ListView):
model = ClubSession
template_name = 'club_sessions.html'
context_object_name = 'all_club_sessions_list'
I'm trying to test the view. My test class has a setUp
which creates a record:
def setUp(self):
ClubSession.objects.create(location='test location',
coach=User(id=1),
date='2020-06-01 18:30',
details='this is another test')
When I run my test I get this error:
IntegrityError: The row in table 'club_sessions_clubsession' with primary key '1' has an invalid foreign key: club_sessions_clubsession.coach_id contains a value '1' that does not have a corresponding value in auth_user.id.
A user with id 1 exists so how do I get this to work? I've tried adding the username but that didn't work either.
I would strongly advise not to use primary keys, especially since dispatching primary keys is the responsibility of the database, and thus that can differ between sessions.
Furthermore tests run on an independent database, so the data stored in the database you use in development or on production is not used.
Probably it is better to first create a user, for example:
from django.contrib.auth.models import User
# …
def setUp(self):
user = User.objects.create(username='foo')
ClubSession.objects.create(
location='test location',
coach=user,
date='2020-06-01 18:30',
details='this is another test'
)