我有一個非常簡單的模型和貓的視圖py文件(試圖測試/學(xué)習(xí)django的基本功能。然而,貓的幸福狀態(tài)從未真正更新過。class Cats(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) name = models.CharField(max_length = 200) description = models.TextField() happiness = 6 def pet(self): self.happiness = self.happiness+1 self.save()from django.shortcuts import render, get_object_or_404from .models import Catsdef cat_detail(request, pk): cat = get_object_or_404(Cats, pk=pk) return render(request, 'cats/cat_detail.html', {'cat': cat})def cat_interact(request, pk, action): cat = get_object_or_404(Cats, pk=pk) pet = False if(action == 1): cat.pet() pet = True return render(request, 'cats/cat_interact.html', {'cat': cat, 'pet': pet})操作將始終為 1(這是當(dāng)前唯一可能的操作)。在“細(xì)節(jié)”和“互動”的html文件中,我打印出了貓的幸福狀態(tài)。當(dāng)我進入交互頁面時,貓的幸福狀態(tài)被打印為7(因為默認(rèn)/開始幸福感為6)。我希望將此值(7)保存到數(shù)據(jù)庫中,當(dāng)我再次轉(zhuǎn)到詳細(xì)信息頁面時,它也打印7。但是,即使在詳細(xì)信息頁面上運行函數(shù) cat.play() 后,它仍然會打印 6,這是默認(rèn)設(shè)置。7 是否從未保存到數(shù)據(jù)庫?在這種情況下,self.save() 不起作用嗎?我應(yīng)該如何更改我的代碼?
1 回答

白衣染霜花
TA貢獻(xiàn)1796條經(jīng)驗 獲得超10個贊
你的沒有連接到你的數(shù)據(jù)庫,你應(yīng)該這樣寫它happiness
class Cats(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE)
name = models.CharField(max_length = 200)
description = models.TextField()
happiness = models.IntegerField(default = 6)
那么這部分
def pet(self):
self.happiness = self.happiness+1
self.save()
將保存到數(shù)據(jù)庫happiness
添加回答
舉報
0/150
提交
取消