【问题标题】:Django: Store List of Users in model?Django:在模型中存储用户列表?
【发布时间】:2015-01-17 01:25:27
【问题描述】:

我希望能够将用户列表(内置 Django 身份验证模块用户)作为字段存储在我的模型中,有点像这样:

class EducationalClass(models.Model):
    students = UserListField()

显然没有 UserListField,所以我的问题是,如何在我的模型中存储用户列表?

【问题讨论】:

    标签: django python-2.7 django-models


    【解决方案1】:

    为什么不使用与您的 User 对象相关的 ManyToMany 字段?

    class EducationalClass(models.Model):
        students = models.ManyToManyField(User)
    

    然后对于任何给定的EducationalClass,您可以访问.students.all().students.filter(...) 以及查询集可用的所有其他方法。

    【讨论】:

    • 如果每个 EducationalClass 只能与一个用户相关,则建议使用 FK - MTM 关系假设每个班级可以有很多学生,每个学生可以属于多个班级。 (这是对现已删除的评论的回复;我会将其留在这里以进行澄清,以防其他人阅读此内容并考虑使用 ForeignKey)
    • 哇哦!我什至不知道 ManyToMany 字段。显然,我需要了解很多关于 Django 的知识……
    • 别担心!在此处查看有关可用字段类型的文档:docs.djangoproject.com/en/1.7/ref/models/fields/#field-types
    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2016-07-15
    • 2014-08-15
    • 2013-04-09
    • 2019-01-01
    • 2020-06-27
    • 2020-05-19
    相关资源
    最近更新 更多