第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

無法理解 Django 中的查詢集

無法理解 Django 中的查詢集

BIG陽 2021-09-11 21:02:23
我有一個連接到模型的用戶個人資料頁面,其中包含以下字段:class Profile(models.Model):? ? user = models.OneToOneField(User, on_delete=models.CASCADE)? ? image = models.ImageField(default='default.jpg', upload_to='profile_pics')這就像它應(yīng)該的那樣工作;加載連接到相關(guān)用戶的個人資料圖像,并區(qū)分用戶。我現(xiàn)在要做的是將一個單獨的圖庫模型連接到個人資料頁面,用戶可能有一個小圖片庫可以隨意使用。畫廊模型如下所示:class GalleryModel(models.Model):? ? user = models.ForeignKey(User, on_delete=models.CASCADE)? ? img_1 = models.ImageField(default='default.jpg', upload_to='images')? ? img_2 = models.ImageField(default='default.jpg', upload_to='images')? ? img_3 = models.ImageField(default='default.jpg', upload_to='images')views.py 文件如下所示:class ProfileDetailView(DetailView):? ? model = Profile? ?# Is something iffy here? Should this refer to the GalleryModel as well?? ? template_name = 'account/view_profile.html'? ? def get_object(self):? ? ? ? username = self.kwargs.get('username')? ? ? ? if username is None:? ? ? ? ? ? raise Http404? ? ? ? return get_object_or_404(User, username__iexact=username, is_active=True)? ? def get_context_data(self, **kwargs):? ? ? ? context = super().get_context_data(**kwargs)? ? ? ? username = self.object.username? ? ? ? context['person'] = GalleryModel.objects.get(user__username=username)? ?#loads username string? ? ? ? context['img_1'] = GalleryModel.objects.last().img_1? ? ? ? context['img_2'] = GalleryModel.objects.last().img_2? ? ? ? context['img_3'] = GalleryModel.objects.last().img_3? ? ? ? return context我嘗試了很多想法(即 filter() 和 get() 方法的各種方法)并仔細檢查https://docs.djangoproject.com/en/2.1/topics/db/queries/,但我無法解決。例如 filter(username__iexact=username) 似乎并沒有解決問題,主題的變化也不會產(chǎn)生任何錯誤消息,我真的不明白。如果我在模板中插入 {{ person }},我可以獲得用戶名,但是如何將對象(圖像)連接到 GalleryModel 中的用戶名?嘗試以下是不行的:GalleryModel.objects.get(user__username=username).img_1和往常一樣,我有一種怪異的感覺,我錯過了一些相當(dāng)簡單的東西:)注意?。何抑?last() 方法顯然不是我應(yīng)該做的,但到目前為止,這是我設(shè)法將圖像渲染到模板的唯一方法。
查看完整描述

1 回答

?
猛跑小豬

TA貢獻1858條經(jīng)驗 獲得超8個贊

如果要將圖庫連接到配置文件,則必須將配置文件添加為外鍵,而不是用戶。

class GalleryModel(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

除非您有其他類型的畫廊,否則請使用 Gallery(models.Model)。


查看完整回答
反對 回復(fù) 2021-09-11
  • 1 回答
  • 0 關(guān)注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號