user2896120
user2896120

Reputation: 3282

Is a follower-following table a many to many relationship?

I have two models. One model is a Users table which contains fields like id, username, email and I have another table which is used to show a follower and following relationship. The Following model is shown:

class Following(models.Model):
    target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE, null=True)
    follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE, null=True)

    def __str__(self):
        return '{} is followed by {}'.format(self.target, self.follower)

I have made this assuming that the relationship between Users and Following is a one to many relationship (One user can have many followers, and can follow many as well). Is this correct? Or should it be a many to many relationship. If so, why? I have seen many instances of this table schema being both many to many and one to many.

User Class:

class User(AbstractBaseUser):
    username    = models.CharField(max_length=15, unique=True)
    email       = models.EmailField(max_length=100, unique=True)
    date_joined = models.DateTimeField(auto_now_add=True,
                                       null=True) 
    active      = models.BooleanField(default=True)
    staff       = models.BooleanField(default=False)
    admin       = models.BooleanField(default=False)

Upvotes: 2

Views: 1537

Answers (1)

Damir Sudarevic
Damir Sudarevic

Reputation: 22187

Using predicates [px] and constraints [cx.y].


[p1] User (UserID) exists.

[c1.1] User is identified by UserID.

user {UserID}  -- p1
 KEY {UserID}  -- c1.1

[p2] Follower (FollowerID) follows author (AuthorID).

[c2.1] Follower is a user.

[c2.2] Author is a user.

[c2.3] For each follower, that follower may follow more than one author.

[c2.4] For each author, that author may be followed by more than one follower.

[c2.5] For each combination of author and follower, that combination of that author and that follower may occur at most once.

[c2.6] Authors may not follow themselves.

following {AuthorID, FollowerID} -- p2
      KEY {AuthorID, FollowerID} -- c2.5, c2.3, c2.4

FOREIGN KEY {FollowerID} REFERENCES user {UserID} -- c2.1
FOREIGN KEY {AuthorID}   REFERENCES user {UserID} -- c2.2

      CHECK AuthorID != FollowerID                -- c2.6

Bottom line, many-to-many. You can always tweak this to reflect your specific needs by focusing on conceptual/logical design expressed in natural language -- predicates and constraints.

Upvotes: 2

Related Questions