Django模型:用户和关注者的数据库设计 [英] Django models: database design for user and follower
问题描述
在Django模型中,我正在创建一个表格关注者",该表格具有:
In Django model I am making a table 'followers', which has:
user's id. (this is followed by)
user's id (this is follower)
这很简单,一个用户可以关注其他用户.
that's simple a user can follow other users.
我应该如何在Django中定义模型?
How should I define the model in Django?
我尝试了此操作,但不起作用:
I tried this, but does not work:
user = models.ForeignKey('self')
follower_id = models.ForeignKey('self')
这应该怎么做?
谢谢
推荐答案
除非您有一个名为self
的模型,否则'self'参数将不起作用.
The 'self' argument won't work unless you have a model called self
.
假设您的分配模型称为Following
,并且您正在使用内置的User
模型,则可以执行以下操作:
Assuming that your assignment model is called Following
, and you're using the built in User
model then you can do:
class Following(models.Model):
target = models.ForeignKey('User', related_name='followers')
follower = models.ForeignKey('User', related_name='targets')
这可能需要进一步的唯一性和验证逻辑.
This will likely need some further uniqueness and validation logic.
Note the related_name
attribute, see https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_name. This means that for a given user object you can do user.targets.all()
to get users they follow, and user.followers.all()
to get users who follow them.
还要注意,Django在ORM中返回目标模型实例,而不是ID.这意味着即使基础表可能被称为follower_id
,在python代码following.follower
中也将返回实际的User对象.
Note also that Django returns target model instances, not IDs, in the ORM. This means that even though the underlying table may be called follower_id
, in the python code following.follower
will return an actual User object.
这篇关于Django模型:用户和关注者的数据库设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!