我的 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 的用戶,那么我該如何讓它工作呢?我試過添加用戶名,但也沒有用。
1 回答

慕村225694
TA貢獻1880條經驗 獲得超4個贊
我強烈建議不要使用主鍵,尤其是因為分派主鍵是數據庫的責任,因此會話之間可能會有所不同。
此外,測試在獨立的數據庫上運行,因此不會使用存儲在您在開發或生產中使用的數據庫中的數據。
可能最好先創建一個用戶,例如:
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'
)
添加回答
舉報
0/150
提交
取消