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")
在贝壳里
In [1]: t = Tweeter()
In [2]: t.save()
In [3]: f = Tweeter()
In [4]: f.save()
In [5]: r=Relationship()
In [6]: r.who=t
In [7]: r.whom=f
In [8]: r.save()
In [18]: Relationship.objects.all()[0].who.id
Out[18]: 1L
In [19]: Relationship.objects.all()[0].whom.id
Out[19]: 2L
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>]
编辑:使用ManyToManyField更有意义,正如评论人士所建议的。用户可以有0-x个用户跟随者,用户可以跟随0-x个用户。
https://docs.djangoproject.com/en/1.3/ref/models/fields/#manytomanyfield
不去查代码,就没什么好说的了。
我就是这样做的:
在贝壳里
首先,你应该了解如何store additional information about users。它需要与一个用户有关系的另一个模型,即“profile”模型。
然后,您可以使用M2M字段,假设您使用django-annoying,您可以这样定义您的用户配置文件模型:
使用它:
另外,请注意,您可以检查/重用像django-subscription、django-actstream、django-social(可能更难使用)这样的应用程序。。。
您可能需要查看用于notifications和activities的django包,因为它们都需要一些后续/订阅数据库设计。
相关问题 更多 >
编程相关推荐