【问题标题】:Enforce a where clause on particular column in django ORM在 django ORM 中的特定列上强制执行 where 子句
【发布时间】:2014-02-17 09:01:14
【问题描述】:

我们可以在 django ORM 周围编写一个包装器,以便每个查询都应该有一个 where 子句吗? 现在,你不能有一个很好的all() 方法。 例如。 假设我们有auth_user 表和user_properties 表,其中包含有关用户的附加数据(以及来自auth_user 的外键)。 在这里,如果开发人员想从 user_properties 表中获取几行,他必须在filter 查询中提供useruser_id 列,否则它应该给出异常。 如果您需要更多信息,请在评论中写下。

【问题讨论】:

    标签: python django django-orm


    【解决方案1】:

    如果您想扩展用户模式,请在user_properties 模型中将 OneToOne 字段用于用户模型,如下所示:

    class UserProperty(models.Model):
        user = models.OneToOneField(User, related_name='properties')
        prop1 = models.CharField(...)
        prop2 = models.CharField(...)
    
    prop1 = request.user.properties.prop1
    

    记住,创建新用户时需要创建 UserProperty

    【讨论】:

    • 这不是我想知道的。该表肯定会被创建。我想知道的是 - 开发人员不能使用 all 方法并强制他在 UserProperty 上的每个查询中至少使用 user 的 filter 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多