Kayla
Kayla

Reputation: 11

How to implement followers/following using ManyToManyField in Django?

I want to implement the following feature using manytomanyfield in my Django Application. I have created UserProfile class for every user with two attributes: user and follows. User inherit the default Django user model.

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name = 'user', on_delete=models.CASCADE)
    follows = models.ManyToManyField("self", related_name = 'follower',symmetrical=False )

I tried this in python shell:

>>> lily = User(username="Lily")
>>> lily.save()
>>> mary = User(username="Mary")
>>> mary.save()
>>> lily_profile = UserProfile(user=lily)
>>> lily_profile.save()
>>> mary_profile = UserProfile(user=mary)
>>> mary_profile.save()
>>> lily_profile.follows.add(mary_profile)

But I got this error after I do lily_profile.follows.add(mary_profile) :

django.db.utils.OperationalError: table polls_userprofile_follows has no column named from_userprofile_id

Does anyone know how to fix this error? Thanks a lot!

Upvotes: 0

Views: 526

Answers (1)

Manan M.
Manan M.

Reputation: 1394

Try deleting your migration file(s) and then rerun below command

python manage.py makemigrations 
python manage.py migrate 

Upvotes: 1

Related Questions