How do I write this "model" in Django?
I am currently using the Django Users model. Very simple. However, I would like to add one more feature: Adding Friends!
I would like to create 2 columns in my table:
UID (user id) friend_id (his friend's id! ... of course this id is also in the Django user model. The UID-friend_id combination must be unique! For example, if my ID is 84, I cannot have two strings the same, because I can only follow the same friend once.
Can anyone tell me if this is the right way to do this? Should I use some KEY relationship for "friend_id", or should I leave it as "IntegerField"?
class Friend(models.Model):
uid = models.ForeignKey(User)
friend_id = models.IntegerField(default=0)
thank
source to share
You should create a model that defines the relationship between two users, and then define two foreign key fields, each one for the user. Then you can add a unique constraint to make sure you don't have duplicates.
There is an article here explaining how to do it: http://www.packtpub.com/article/building-friend-networks-with-django-1.0
An example of a model from this 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'), )
source to share