亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Django 測試設置中創建包含用戶的記錄

如何在 Django 測試設置中創建包含用戶的記錄

子衿沉夜 2022-12-14 20:52:32
我的 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'

    )


查看完整回答
反對 回復 2022-12-14
  • 1 回答
  • 0 關注
  • 72 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號