对于我的应用程序,我想向默认用户模型 (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)
泛舟湖上清波郎朗
相关分类