Django 上的用户追随者模型。不能在指定中间模型的 ManyToManyField 上使用 add()。请改用 accounts.Contact 的经理

User Follower model on Django. Cannot use add() on a ManyToManyField which specifies an intermediary model. Use accounts.Contact's Manager instead

我是 Django 的新手,请原谅代码或逻辑中的任何愚蠢错误,

简介: 我正在尝试在 Django 中创建一个用户关注者模型。用户可以在哪里关注和取消关注网站上的其他用户

错误: 我为我的 follow/unfollow 做了 models 我也做了 views 我收到这个错误

AttributeError at /accounts/admin/follow/
Cannot use add() on a ManyToManyField which specifies an intermediary model. Use accounts.Contact's Manager instead. 

obj.followers.add(user) 在回溯中突出显示为错误的来源

下面是我的models.py

from django.contrib.auth.models import User
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=100)
    country = models.CharField(max_length=100)
    def get_absolute_url(self):
        return reverse('accounts:profile', kwargs={'username': self.user.username})

class Contact(models.Model):
    user_from = models.ForeignKey(User, related_name='suppporter')
    user_to = models.ForeignKey(User, related_name='leader')

    def __str__(self):
        return '{} follows {}'.format(self.user_from, self.user_to)


User.add_to_class('following',
                  models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False))

我觉得models.py可能不错。我认为错误在于我的观点。 下面是我的view.py

class FollowToggle(LoginRequiredMixin, RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        username = self.kwargs.get('username')
        print(username + " This is the user who will be followed") # This prints correct
        profile = get_object_or_404(Profile, user__username=username)
        print(profile) # This prints correct
        obj = get_object_or_404(User, username=username)
        print(obj) # This prints correct
        url_ = profile.get_absolute_url()
        print(url_) # This prints correct
        user = self.request.user
        print(user) # This prints correct
        if user.is_authenticated():
            if user in obj.followers.all(): # I know this is the source of the error.
                obj.followers.remove(user)
            else:
                obj.followers.add(user)
        return url_

下面是Urls.py以防万一

url(r'^(?P<username>[-\w]+)/follow/$', views.FollowToggle.as_view(), name='follow'),

您不能对通过第三个模型定义的多对多关系使用 addremove 方法。来自 docs:

Unlike normal many-to-many fields, you can’t use add(), create(), or set() to create relationships

您应该使用 Contact 经理:

if user.is_authenticated():
    if user in obj.followers.all(): # I know this is the source of the error.
        Contact.objects.filter(user_to=obj, user_from=user).delete()
    else:
        Contact.objects.create(user_to=obj, user_from=user)

在 Django 2.2 中,您可以使用 addremoveset 方法 (Docs)

You can also use add(), create(), or set() to create relationships, as long as your specify through_defaults for any required fields