Django 模型:用户和关注者的数据库设计 [英] Django models: database design for user and follower

查看:44
本文介绍了Django 模型:用户和关注者的数据库设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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.

注意 related_name 属性,请参阅 https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_name.这意味着对于给定的用户对象,您可以执行 user.targets.all() 以获取他们关注的用户,并使用 user.followers.all() 获取关注的用户关注他们.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆