我正在玩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很可能是的,但它也可以被视为一个问题。因为我没有线索开始,所以我问了一下。 –