如何在Django测试中创建一个包含用户的记录setUp

问题描述 投票:1回答:1

在我的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的用户存在,我怎么才能让它工作?我试过添加用户名,但也没有用。

python django python-3.x django-testing
1个回答
2
投票

我强烈建议 使用主键,特别是调度主键是数据库的责任,因此在不同的会话中会有所不同。

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

可能最好是先 创造 比如说,一个用户。

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'
    )
© www.soinside.com 2019 - 2024. All rights reserved.