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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何添加到默認(rèn) Django 用戶模型的 ManyToManyField 擴(kuò)展?

如何添加到默認(rèn) Django 用戶模型的 ManyToManyField 擴(kuò)展?

鴻蒙傳說(shuō) 2023-05-16 09:50:22
對(duì)于我的應(yīng)用程序,我想向默認(rèn)用戶模型 (django.contrib.auth.models.User) 添加一個(gè)額外的 ManyToManyField。這個(gè)額外的字段稱為“收藏夾”,用戶收藏的帖子應(yīng)該放在那里。這就是我所擁有的:class Favorite(models.Model):    user = models.OneToOneField(User, related_name='favorites', on_delete=models.CASCADE)    favorites = models.ManyToManyField(Recipe, related_name='favorited_by')這是我嘗試從 shell 添加到“收藏夾”時(shí)得到的結(jié)果。# imported Recipe, Favorite, User(default)>>> recipe1 = Recipe.objects.all()[0]>>> me = User.objects.all()[0]>>> me.favorites.add(recipe1)django.contrib.auth.models.User.favorites.RelatedObjectDoesNotExist: User has no favorites.# Just checking if the the User object, me, has a 'favorites' attribute>>> 'favorites' in dir(me)True將 Recipe 對(duì)象添加到此“收藏夾”字段的正確方法是什么?為了獲得更多參考,我做了一些類似于我處理用戶之間的友誼的事情,但它更簡(jiǎn)單一些,因?yàn)槲覜](méi)有擴(kuò)展用戶模型。該代碼如下并且工作正常:class Friend(models.Model):    users = models.ManyToManyField(User)    current_user = models.ForeignKey(User, related_name='owner', null=True, on_delete=models.CASCADE)    @classmethod    def make_friend(cls, current_user, new_friend):        friend, created = cls.objects.get_or_create(            current_user=current_user        )        friend.users.add(new_friend)    @classmethod    def lose_friend(cls, current_user, new_friend):        friend, created = cls.objects.get_or_create(            current_user=current_user        )        friend.users.remove(new_friend)
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊

解決。我的解決方案如下,但我不確定這是否是好的做法。


django.contrib.auth.models.User.favorites.RelatedObjectDoesNotExist: User has no favorites.

用戶模型可能有“收藏夾”字段,但我需要用“收藏夾”對(duì)象實(shí)際填充它。我通過(guò)在我的 views.py 中編寫一個(gè)函數(shù)來(lái)做到這一點(diǎn):


def add_favorite(request, pk):

    # Check if the user has a favorites field. If not create one and add. If yes, just add

    user_favorites, created = Favorite.objects.get_or_create(

        user=request.user

        )

    recipe = get_object_or_404(Recipe, pk=pk)

    user_favorites.favorites.add(recipe)

這似乎可行,我現(xiàn)在可以訪問(wèn)用戶的收藏夾,但我可能這不是一個(gè)好習(xí)慣。使用我的方法,創(chuàng)建的新模型中沒(méi)有“收藏夾”對(duì)象。只有當(dāng)用戶決定添加最喜歡的食譜時(shí)才會(huì)創(chuàng)建它,如果它不存在,上面的視圖將創(chuàng)建一個(gè)。


查看完整回答
反對(duì) 回復(fù) 2023-05-16
  • 1 回答
  • 0 關(guān)注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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