我正在玩Django/python中的關係,我想知道你們是如何在用戶和他的追隨者之間創建關係的,以及他遵循的用戶是追隨者。以下用戶喜歡Django中的twitter,你會怎麼做?
很想讀你的意見了......
我正在玩Django/python中的關係,我想知道你們是如何在用戶和他的追隨者之間創建關係的,以及他遵循的用戶是追隨者。以下用戶喜歡Django中的twitter,你會怎麼做?
很想讀你的意見了......
首先,您應該瞭解如何store additional information about users。它需要與一個用戶相關的另一個模型,即「簡介」模型。
然後,你可以使用一個M2M領域,假設你使用django-annoying,你可以定義用戶配置文件模型,例如:
from django.db import models
from annoying.fields import AutoOneToOneField
class UserProfile(models.Model):
user = AutoOneToOneField('auth.user')
follows = models.ManyToManyField('UserProfile', related_name='followed_by')
def __unicode__(self):
return self.user.username
而且使用它作爲這樣的:
In [1]: tim, c = User.objects.get_or_create(username='tim')
In [2]: chris, c = User.objects.get_or_create(username='chris')
In [3]: tim.userprofile.follows.add(chris.userprofile) # chris follows tim
In [4]: tim.userprofile.follows.all() # list of userprofiles of users that tim follows
Out[4]: [<UserProfile: chris>]
In [5]: chris.userprofile.followed_by.all() # list of userprofiles of users that follow chris
Out[5]: [<UserProfile: tim>]
此外,請注意,您可以檢查/重新使用像django-subscription,django-actstream,django-social(難以使用的可能)應用程序...
Y ou可能想看看notifications和activities的django包,因爲它們都需要一些關注/訂閱數據庫設計。
我已經創建了UserProfile。我認爲我應該去的很多很多球場。但在這一行chris.userprofile.followed_by.all()< - 你定義了一個followed_by函數嗎? –
其實,followed_by是UserProfile.follows字段的** related_name **。默認情況下,它將是userprofile_set,這不是真正的信息。 – jpic
啊是的,現在我看到謝謝@ jpic –
編輯:更有意義,使用ManyToManyField,作爲評論者建議。用戶可以有0-x用戶關注者,用戶可以關注0-x用戶。
https://docs.djangoproject.com/en/1.3/ref/models/fields/#manytomanyfield
沒有進入代碼,沒有太多可說的了。
這是我會怎麼做:
class Tweeter(models.Model):
user = models.ManyToManyField('self', symmetrical=False, through='Relationship')
class Relationship(models.Model):
who = models.ForeignKey(Tweeter, related_name="who")
whom = models.ForeignKey(Tweeter, related_name="whom")
在殼,
在[1]:T =高音揚聲器()
在[2]:噸。保存()
在[3]:F =高音揚聲器()
在[4]:f.save()
在[5]:R =關係()
在[6]:= r.who噸
在[7]:r.whom = F
在[8]中:r.save()
在[18]:Relationship.objects.all()[0] .who.id
缺貨[18]:1L在[19]:Relationship.objects。 all()[0] .whom.id
Out [19]:2L
除非您有特定的與編程相關的問題,否則這更適合作爲論壇中的帖子。 – patrickn
@patrickn很可能是的,但它也可以被視爲一個問題。因爲我沒有線索開始,所以我問了一下。 –