如何在 Django 测试设置中创建包含用户的记录

How to create a record that contains a user in Django test setUp

我的 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'

我正在尝试测试视图。我的测试 class 有一个 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.<b>create(</b>username='foo'<b>)</b>
    ClubSession.objects.create(
        location='test location',
        coach=<b>user</b>,
        date='2020-06-01 18:30',
        details='this is another test'
    )