我正在尝试构建一个应用程序,让人们查看政客发布的tweet,我正在努力寻找正确的方法来指定Twitter上的用户和离线用户之间的关系。例如,一个政客可能有两个Twitter帐户,这些帐户可能提到另外三个不是政客的Twitter用户。现在,我有一个用户表,其中包含来自Twitter API的信息(例如,关注者的数量,tweets的数量),它将包含来自政客账户和他提到的那些人的Twitter信息,还有一个包含立法者信息的立法者表(例如,政党、商会)。在
我该如何为Django正确设置模型?如何在模板中同时访问用户和立法者信息?通过下面的设置,我无法从user.legitor_集. 在
class User(models.Model):
id = models.IntegerField(primary_key=True)
twitter_id = models.CharField(max_length=21, unique=True)
twitter_name = models.CharField(max_length=55, unique=True)
fullname = models.CharField(max_length=45)
followers = models.IntegerField()
following = models.IntegerField()
favorites = models.IntegerField()
tweets = models.IntegerField()
timezone = models.CharField(max_length=45, blank=True)
class Legislator(models.Model):
id = models.IntegerField(primary_key=True)
last_name = models.CharField(max_length=17, blank=True)
first_name = models.CharField(max_length=11, blank=True)
chamber = models.CharField(max_length=3, blank=True)
state = models.CharField(max_length=2, blank=True)
party = models.CharField(max_length=11, blank=True)
twitter_id = models.ForeignKey(User, to_field = "twitter_id", related_name="%(app_label)s_%(class)s_id")
twitter = models.ForeignKey(User, to_field = "twitter_name", related_name="%(app_label)s_%(class)s_name")
利比。如果我理解您的需求,这似乎是使用ForeignKey字段的多对一关系的最简单的起点。(这与兰兹的建议基本相同。)
在Python代码中,给定一个twitter帐户
u
和立法者l
,可以运行u.legislator = l
将立法者与twitter帐户关联起来。你也可以用l.user_set.add(u)
来表示,考虑到这些模型,这对我来说更有意义。在类似地,您可以使用
Legislator.user_set
来访问twitter帐户的RelatedManager。当你想使用相关的模型(任何/所有相关的twitter帐户)而不是你拥有的(立法者)模型时,你可以在模板中循环或者进行额外的查询。在还有一些用法示例in the docs。在
在
ForeignKey
字段中,我设置blank=True, null=True
使关系成为可选的。除非在字段的选项中另有指定,否则Django将在User
表中创建并使用legislator_id
列来管理关系。在相关问题 更多 >
编程相关推荐