我希望用户能够互相关注(每个用户都可以关注并跟随多个用户)。使用ForeignKeys表示它有什么问题吗?
class Follow(models.Model):
followed=models.ForeignKey(User, unique=True)
follower=models.ForeignKey(User,related_name="follower")
def __unicode__(self):
return self.followed
答案 0 :(得分:2)
最好在Person
或User
课程中使用ManyToMany with self。例如:
class Person(models.Model):
first_name = CharField(max_length=50)
followers = ManyToMany("self", related_name="following")
这样,代码少得多,您可以执行以下操作:
p = Person.objects.get(first_name="bob")
p.following.all() # Everyone bob is following
p.followers.all() # Everyone that is following bob
有关ManyToMany with self的更多信息,请参阅Django文档。