Home > front end >  How do you add one object to a Django Model that has a ManyToManyField?
How do you add one object to a Django Model that has a ManyToManyField?

Time:07-07

I am trying to create a social media type site that will allow a user to follow and unfollow another user. followers has a ManyToManyField because a user can have many followers.

models.py

class Follower(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    followers = models.ManyToManyField(User, related_name="followers")

views.py

def username(request, user):
    #get user
    user = get_object_or_404(User.objects, username=user)
    posts = Post.objects.filter(user=user).order_by('-date_and_time')

    #follow button code
    follow_or_unfollow = ''
    try:
        following = get_object_or_404(Follower, Q(
            user=user) & Q(followers=request.user))
        print(following)
    except: 
        following = False

    if following:
        follow_or_unfollow = True
    else:
        follow_or_unfollow = False

    if request.POST.get('follow'):
        follower = Follower.objects.create(user=request.user)
        follower.followers.add(*user)
        follow_or_unfollow = False
    elif request.POST.get('unfollow'):
        follow_or_unfollow = True
        #following.delete()

When it gets the 'follow' POST request, I want it to add the user who sent it (the one that is logged in) to be added to the followers. Right now, I am getting this error when I try to do that.

TypeError: django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager.add() argument after * must be an iterable, not User

I know it says that it has to be iterable, but is there any way to just add one object at a time. Also, how would you delete this particular object?

CodePudding user response:

The * in the arguments converts a list to individual args. For example-

lst = [1,2,3,4,5]

function(*lst)

can be just read as

function(1,2,3,4,5)

You have used follower.followers.add(*user). Hence, user must be an iterable to be unpacked and passed as a list or arguments. But user is a single User object.

You should just use follower.followers.add(user) in this case.

  • Related