为了账号安全,请及时绑定邮箱和手机立即绑定

如何添加到默认 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 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信