masterofdestiny
masterofdestiny

Reputation: 2811

Django : Many TO many relationship for same table

I have a scenario .

I have many users in my application and everyone one have there own (Trusted Circle).Trusted Circle is shomewhat similar to the close friend .

I am having a confusion here .

What is the best way to implement the trusted circle per user .Trusted circle users are also like user in my app .

I heared about ManyToMany field with self attribute .It worth to use in my application to maintain the trusted circle per user .

Please suggest me some other alternatives also if possible .

Upvotes: 2

Views: 2715

Answers (2)

Pran Kumar Sarkar
Pran Kumar Sarkar

Reputation: 1003

To add many to many relationship to a single table, add a different related_name for the fields which has many to many relationship with a single table.

For eg:

class A(models.Model):
    field1 = models.ManyToManyField('B', related_name='field1')
    field2 = models.ManyToManyField('B', related_name='field2')
    field3 = models.ManyToManyField('B', related_name='field3')

class B(models.Model):
    name = models.CharField(max_length=30, unique=True)

Upvotes: 0

dani herrera
dani herrera

Reputation: 51735

Classical approach will be:

1 user circle can contains n users
1 user may be in n user circles.

This is a N:M relationship.

But, because this is for django, my django design suggestion is:

1:1 relationship to circle:
      1 user has 1 circle   

N:M relationship to users circle:
      1 circle can contains n users
      1 user may be in n circles.

Circle with one to one and m2m Relationhips:

class Circle(models.Model):
    owner = models.OneToOneField(User, primary_key=True)
    users = models.ManyToManyField(User)

To create user's circle on create user:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

def create_circle(sender, **kw):
    user = kw["instance"]
    if kw["created"]:
        c = Circle(user=user)
        c.save()

post_save.connect(create_circle, sender=User)

Enjoy and enroll me on your trusted circle ;)

Upvotes: 2

Related Questions