Franz
Franz

Reputation: 245

Django ManyToMany relation - check for existence?

I am currently learning Django and building a twitter-like app for that purpose.

I have used a ManyToManyField in my Profile model to reflect followers as such:

models.py

class Profile(models.Model):
    """
        Extension of User model to save additional information
    """
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    followers = models.ManyToManyField('self', related_name='Followers', blank=True, symmetrical=False)
    follower_count = models.IntegerField(default=0)
    following_count = models.IntegerField(default=0)

Now I am trying to check if a user is already following another user (when opening the profile so that I can display the correct follow/unfollow button there)

views.py

def profile(request, username):
    try:
        user = User.objects.get(username=username)
        user_profile = Profile.objects.get(user_id=user.id)
    except ObjectDoesNotExist:
        raise Http404("User does not exist")
    is_following = True if user.id in Profile.followers.all() else False

    return render(request, 'songapp/profile.html', {'user_profile': user_profile,
                                                    'user'        : user,
                                                    'is_following': is_following})

The issue lies within

Profile.followers.all()

As I get the following AttributeError:

'ManyToManyDescriptor' object has no attribute 'all'

I already used the search function and read through results up to 8 years old but I either did not find or understand the corresponding answer.

Any help is highly appreciated

EDIT: A picture of the Model Modelpicture

Upvotes: 0

Views: 119

Answers (1)

Franz
Franz

Reputation: 245

Thanks to https://stackoverflow.com/users/4996863/charnel

I got to try migrations again and I really missed one of them. Ran manage.py makemigrations and manage.py migrate to get my model working.

Upvotes: 1

Related Questions