【问题标题】:How to create a record that contains a user in Django test setUp如何在 Django 测试集中创建包含用户的记录
【发布时间】:2020-09-17 13:49:00
【问题描述】:

我的 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 的用户,那么我该如何让它工作呢?我试过添加用户名,但也没有用。

【问题讨论】:

  • 测试在不同的数据库上运行,因此“标准”数据库中不存在数据。
  • User(id=1) 未保存到数据库中。所以不能作为外键链接。

标签: python django python-3.x django-testing


【解决方案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'
    )

【讨论】:

  • 完美。这正是我想要的。很高兴了解独立数据库。我从来没想到。我会在几分钟内接受答案。
猜你喜欢
  • 1970-01-01
  • 2016-08-03
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多