Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use ManyToManyField for self class

I have one Model inside my models.py named Account
In this case I wanna create a field in which I can choose my own Model Objects.
for example if I had 3 Accounts {Jack, Harry, Helena}
I want to choose the accounts I want between them. Actually I just want to create a Following System. Jack can follow Harry and Helena & also Helena can follow Jack or Harry
How can I do that guys?

Account class inside models.py

class Account(models.Model):
    username = models.CharField(max_length=100)
    following = models.ManyToManyField(**Account**, blank=True)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

to create a following system, you can use Django’s ManyToManyField. This field is used to create many-to-many relationships i.e., a relationship where an object can belong to multiple categories and a category will also have multiple objects.

In your Account model, you can add a field named ‘following’ and set it as a ManyToManyField to ‘self’. This means an account can have many other accounts associated with it, which corresponds to the accounts it is following.

Here’s a corrected version of your code:

class Account(models.Model):
    username = models.CharField(max_length=100)
    following = models.ManyToManyField('self', blank=True, symmetrical=False)

The ‘symmetrical=False’ argument is used here to indicate that if Jack is following Harry, it doesn’t necessarily mean that Harry is following Jack.

You can then add or remove accounts by using the add() or remove() method on the ‘following’ field. For example, if you want Jack to follow Harry, you can do:

jack = Account.objects.get(username='Jack')
harry = Account.objects.get(username='Harry')
jack.following.add(harry)

And if you want Jack to unfollow Harry, you can do:

jack.following.remove(harry)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading