如何在 Django test set Up 中创建包含用户的记录



我的Django应用程序中有这个模型:

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

此视图实现它:

class SessionListView(ListView):
model = ClubSession
template_name = 'club_sessions.html'
context_object_name = 'all_club_sessions_list'

我正在尝试测试视图。我的测试类有一个创建记录的setUp

def setUp(self):
ClubSession.objects.create(location='test location',
coach=User(id=1),
date='2020-06-01 18:30',
details='this is another test')

当我运行测试时,出现此错误:

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.

存在 ID 为 1 的用户,那么如何使其工作?我尝试添加用户名,但这也不起作用。

我强烈建议不要使用主键,特别是因为调度主键是数据库的责任,因此会话之间可能会有所不同。

此外,测试在独立的数据库上运行,因此不会使用存储在开发或生产中使用的数据库中的数据。

可能最好先创建一个用户,例如:

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'
)

最新更新