Django ORM 类似于 Pony ORM 中的选择查询

Posted

技术标签:

【中文标题】Django ORM 类似于 Pony ORM 中的选择查询【英文标题】:Django ORM like select query in Pony ORM 【发布时间】:2021-09-29 15:11:27 【问题描述】:

我现在要去 Pony ORM 我已经创建了这样的数据库模型:

class RSSSource(db.Entity):
    title = Required(str, max_len=100)
    link = Required(str, max_len=800)
    key = Required(str, max_len=200)
    description = Required(str, max_len=800)
    is_deleted = Optional(bool, sql_default=False)
    rss_content = Set('RSS', reverse='source')
    subscriptions = Set("Subscription", reverse='source')

    def __str__(self):
        return self.title

class RSS(db.Entity):
    title = Optional(str, max_len=300)
    link = Optional(str, max_len=500)
    description = Required(str, max_len=500)
    source = Optional("RSSSource", reverse="rss_content")
    pub_date = Optional(datetime)
    is_deleted = Optional(datetime, sql_default=False)
    likes = Set("Like", reverse="rss")

    def __str__(self):
        return self.title

class User(db.Entity):
    first_name = Optional(str, max_len=100)
    last_name = Optional(str, max_len=100)
    username = Required(str, max_len=200, unique=True)
    password = Required(str, max_len=500)
    is_deleted = Optional(bool, sql_default=False)
    subscriptions = Set("Subscription", reverse="user")
    likes = Set("Like", reverse="user")

    def __str__(self):
        return self.username

class Subscription(db.Entity):
    source = Optional("RSSSource", reverse="subscriptions")
    user = Optional("User", reverse="subscriptions")
    is_deleted = Optional(bool, sql_default=False)

现在我想执行一个类似于 Django ORM 的选择查询。像这样:

select user.id
from Subscription where source.key = $key and (is_deleted is null or is_deleted = FALSE)

我找不到这样做的方法。有人可以帮忙吗?

【问题讨论】:

【参考方案1】:

我终于想出了类似的方法,并且成功了。

select user
from Subscription as s
left join RSSSource as rs on rs.id = s.source
where rs.key = $key and (s.is_deleted is null or s.is_deleted = FALSE)

【讨论】:

以上是关于Django ORM 类似于 Pony ORM 中的选择查询的主要内容,如果未能解决你的问题,请参考以下文章

带有 Pony ORM 的 Postgres 模式

如何做类似 Django 模型的元类技巧

Django之ORM字段及查询

Django之ORM字段及查询

Django的orm中get和filter的不同

Django:我们可以使用 django ORM 将 dict 直接加载到数据库吗