簡體   English   中英

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

[英]How can you add to a ManyToManyField extension of the default Django User model?

對於我的應用程序,我想向默認用戶 model (django.contrib.auth.models.User) 添加一個額外的 ManyToManyField。 這個額外的字段稱為“收藏夾”,用戶收藏的帖子應該在 go 那里。 這就是我所擁有的:

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

將配方 object 添加到此“收藏夾”字段的正確方法是什么?

為了獲得更多參考,我在處理用戶之間的友誼時做了類似的事情,但它更簡單一些,因為我沒有擴展用戶 model。 代碼如下並且工作正常:

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)

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

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

用戶 model 可能有“收藏夾”字段,但我實際上需要用“收藏夾”object 填充它。 我通過在我的views.py中寫了一個function來做到這一點:

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)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM