
用戶 models.py

class UserProfile(models.Model):
user= models.OneToOneField(User)話題回復(fù) models.py
class Reply(models.Model):
content= models.TextField()
author= models.ForeignKey(User)
...
thanks= models.ManyToManyField(User,related_name='+')每個(gè)reply就是一個(gè)的回復(fù)。每獲得一個(gè)贊同那么thanks就多一對(duì)應(yīng)關(guān)系
我想通過指定用戶然后過濾出所有他的回復(fù),然后獲得他獲得贊同的總數(shù)。
在views視圖中我可以通過如下代碼獲取到一個(gè)人獲得“贊”的總數(shù)
thanks_count = 0
for reply in Reply.objects.filter(author=user_profile.user):
thanks_count+= reply.thanks.count()然后在reply_thanks.html模板中我使用thanks_count就可以獲得獲贊總數(shù)了。
------
上面的方法沒多久就發(fā)現(xiàn)了弊端。由于在貼子界面每個(gè)用戶的頭像旁邊也需要顯示獲得的贊數(shù),多個(gè)人的話,“author=user_profile.user”這個(gè)就用不了了。
所以需要一個(gè)新的,簡(jiǎn)單,可用性高的方法。我想過在UserProfile中添加贊的屬性,或是在取出的回復(fù)的地方套層循環(huán)然后獲取用戶。但是都感覺麻煩,而且不給力,不知道怎么具體實(shí)現(xiàn)。
于是,我又開始翻看模板中的代碼,看能不能找到點(diǎn)什么。我在index.html看到了“{{item.author.get_profile.slug}}”這個(gè)東西。話題可以獲取到用戶,我能不能通過用戶獲取到他獲得的thanks數(shù)呢?
答案是肯定的。
Reply和UserPrefile的聯(lián)系是通過User建立的。那么在模板中使用{{ item.author.userprofile.get_user_thanks }}就可以獲取到UserPrefile中的方法了。值得注意的是那個(gè)userprefile是小寫的。而且如果獲取到了User,那么直接就可以獲取到了userprefile。
確實(shí)是又有所收獲。
接下來的定義get_user_thanks就簡(jiǎn)單了。在UserProfile中增加函數(shù)即可
class UserProfile(models.Model):
user= models.OneToOneField(User)
def get_user_thanks(self):
thanks_count= 0
for reply in Reply.objects.filter(author=self.user):
thanks_count+= reply.thanks.count()
return thanks_count這樣,在模板中,無論是話題還是回復(fù),簡(jiǎn)單的套一下就都可以方便的使用這個(gè)方法獲取用戶贊數(shù)了。
網(wǎng)站名稱:Django查詢的瑣碎記錄-創(chuàng)新互聯(lián)
本文鏈接:http://www.chinadenli.net/article10/dodsdo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供電子商務(wù)、品牌網(wǎng)站制作、搜索引擎優(yōu)化、動(dòng)態(tài)網(wǎng)站、小程序開發(fā)、營(yíng)銷型網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)