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

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

如何添加到默認 Django 用戶模型的 ManyToManyField 擴展?

如何添加到默認 Django 用戶模型的 ManyToManyField 擴展?

鴻蒙傳說 2023-05-16 09:50:22
對于我的應用程序,我想向默認用戶模型 (django.contrib.auth.models.User) 添加一個額外的 ManyToManyField。這個額外的字段稱為“收藏夾”,用戶收藏的帖子應該放在那里。這就是我所擁有的:class Favorite(models.Model):    user = models.OneToOneField(User, related_name='favorites', on_delete=models.CASCADE)    favorites = models.ManyToManyField(Recipe, related_name='favorited_by')這是我嘗試從 shell 添加到“收藏夾”時得到的結果。# 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 對象添加到此“收藏夾”字段的正確方法是什么?為了獲得更多參考,我做了一些類似于我處理用戶之間的友誼的事情,但它更簡單一些,因為我沒有擴展用戶模型。該代碼如下并且工作正常: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貢獻1818條經驗 獲得超3個贊

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


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

用戶模型可能有“收藏夾”字段,但我需要用“收藏夾”對象實際填充它。我通過在我的 views.py 中編寫一個函數來做到這一點:


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)

這似乎可行,我現在可以訪問用戶的收藏夾,但我可能這不是一個好習慣。使用我的方法,創建的新模型中沒有“收藏夾”對象。只有當用戶決定添加最喜歡的食譜時才會創建它,如果它不存在,上面的視圖將創建一個。


查看完整回答
反對 回復 2023-05-16
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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