2009-10-09 34 views
2

我目前正在使用Django用戶模型。 非常簡單。不過,我想添加一個功能:添加好友!如何在Django中編寫這個「模型」?

我想在我的表中創建2列:

UID(用戶的ID) friend_id(他的朋友的ID ......當然,這個ID也是Django的用戶模型 UID-friend_id組合必須是唯一的!例如,如果我的ID是84,我不能有兩行相同,因爲我只能訂閱同一個朋友一次。正確的方法呢?我應該爲「friend_id」做一些KEY關係,還是應該像這樣保留它作爲「IntegerField」?

class Friend(models.Model): 
    uid = models.ForeignKey(User) 
    friend_id = models.IntegerField(default=0) 

謝謝

+4

不是一個答案,但建議。您可能不想將「_id」附加到您的Django字段名稱中。模型屬性「朋友」代表一個實際的朋友實例,而不是朋友的ID。爲了得到id,你最終會做一些像Friend.friend_id.id。另外,如果您要查看數據庫,則會看到Django將該列生成爲friend_id_id。它照顧做foreignkey/id的東西。該屬性表示一個實際的對象。 – 2009-10-09 09:10:21

回答

11

您應該創建一個定義了兩個用戶之間的關係的模型,然後定義兩個外資重點領域,每一個給用戶。然後你可以添加一個唯一的約束來確保你沒有重複。

這裏有一個確切的文章,解釋如何做到這一點:http://www.packtpub.com/article/building-friend-networks-with-django-1.0

從該網頁示例模型:

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'),)