robjeiter
robjeiter

Reputation: 197

Many to Many Relationship in django model

I am currently trying to design my django models for the following situations: I have a class that is called User and every user has a unique userid. Now I want to do a ranking, based on the coins a user has. However, I want to make only users that are friends visible to the user when the user views the ranking.

Therefore I am defining a class Friends that has a ManytoMany field “isfriend” that contains all the userids that the User is friends with. However, I feel that the way I am trying to do this is not the best way to go. Any suggestions how I should implement this?

class User(models.Model):
    userid = models.CharField(max_length=26,unique=True)
    coins = models.IntegerField()

def __str__(self):
    return self.userid

class Friends(models.Model):
    isfriend = models.ManytoManyField(User)

    def __str__(self):
        return self.isfriend

Upvotes: 0

Views: 1193

Answers (1)

Fcmam5
Fcmam5

Reputation: 6942

User has Many User (friends), it gives a solution like:

class User(models.Model):
    userid = models.CharField(max_length=26,unique=True)
    coins = models.IntegerField()
    friends = models.ManyToManyField('self')

    def __str__(self):
        return self.userid

Sorry for my poor English.

Upvotes: 5

Related Questions