Reputation: 271824
I am currently using Django Users model. Very simple. However, I'd like to add one feature: Adding friends!
I would like to create 2 columns in my table:
UID (the ID of the User) friend_id (the ID of his friend! ...of course, this ID is also in Django's User model. The UID-friend_id combination must be unique! For example, if my ID is 84, I cannot have two rows the same, because I can only subscribe to the same friend once.
Can anyone tell me if this is the right way to do it? Should I do some KEY relationship for the "friend_id", or should I leave it like this, as "IntegerField"?
class Friend(models.Model):
uid = models.ForeignKey(User)
friend_id = models.IntegerField(default=0)
Thank you
Upvotes: 2
Views: 396
Reputation: 15493
You should create a model that defines the relationship between two users, and then define two foreign-key fields, each one to a User. You can then add a unique constraint to make sure you don't have duplicates.
There is a article here explaining exactly how to do this: http://www.packtpub.com/article/building-friend-networks-with-django-1.0
The example model from that page:
class Friendship(models.Model):
from_friend = models.ForeignKey(
User, related_name='friend_set'
)
to_friend = models.ForeignKey(
User, related_name='to_friend_set'
)
def __unicode__(self):
return u'%s, %s' % (
self.from_friend.username,
self.to_friend.username
)
class Meta:
unique_together = (('to_friend', 'from_friend'), )
Upvotes: 11