Stephen Goeddel
Stephen Goeddel

Reputation: 31

Django using add to add a ManyToManyField where the object is 'self'

When I execute the following code profile is added to user_profile.following as was expected, but user_profile is also added to profile.following (this is unwanted) why is this happening, I have a feeling it has something to do with the ForeignKey being 'self', but I'm not sure how to fix it...Here is the view:

def follow(request, profile_id):
    user = request.user
    profile = get_object_or_404(Profile, pk=profile_id)
    user_profile = get_object_or_404(Profile, pk=user.id)

    user_profile.following.add(profile)


    return HttpResponseRedirect(reverse('twitter:profile', args=(profile.id,)))

and the model:

class Profile(models.Model):
    user = models.ForeignKey(User)
    bio = models.TextField()
    image = models.ImageField(upload_to='images/%Y/%m/%d/')
    following = models.ManyToManyField('self')

Upvotes: 2

Views: 95

Answers (1)

Stephen Goeddel
Stephen Goeddel

Reputation: 31

Well I finally found the answer to this after some more snooping, in case anyone else wants to know the solution: in the model, following should be

following = models.ManyToManyField('self', symmetrical=False)

Upvotes: 1

Related Questions