【问题标题】:Django ORM: Group by and SQL AgregationDjango ORM:分组和 SQL 聚合
【发布时间】:2018-08-19 05:42:43
【问题描述】:

我知道那里存在任何相同的主题,但没有描述我的情况:(

我在下面有一个模型:

class SecurityPrice (models.Model):
    security    = models.ForeignKey(Security, on_delete = models.CASCADE)
    created     = models.DateTimeField()
    price       = models.FloatField()

    class Meta:
        ordering = ('-created',)

    def __unicode__(self):
        return u'%s - %s - %s' % (self.created, self.security.ticker, self.price)

或在 sqlite 中:

CREATE TABLE IF NOT EXISTS "restful_api_securityprice" 
("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, 
"created" datetime NOT NULL, 
"price" real NOT NULL, 
"security_id" integer NOT NULL REFERENCES "restful_api_security" ("id"));

我想选择每张证券纸的最后价格

在原始 SQL 中,我可以使用这样的 SQL 请求:

SELECT MAX(created), security_id, price as created 
FROM restful_api_securityprice GROUP BY security_id;

以下一些示例以了解我的需求:

表中的所有记录

sqlite> SELECT * FROM restful_api_securityprice;
1|2018-01-07 23:13:02|920.0|1
2|2018-01-07 23:13:43|137.12|2
3|2018-01-07 23:13:58|147.3|3
4|2018-01-09 00:46:29|920.0|1
5|2018-01-09 00:47:27|137.12|2
6|2018-01-09 00:48:08|147.3|3

我需要的东西

sqlite> SELECT MAX(created), security_id, price as created FROM restful_api_securityprice GROUP BY security_id;
2018-01-09 00:46:29|1|920.0
2018-01-09 00:47:27|2|137.12
2018-01-09 00:48:08|3|147.3

在原始 SQL 中没关系。但是如何在不包含原始 sql 的情况下在 Django ORM API 中做同样的事情?

【问题讨论】:

    标签: sql django django-models django-orm


    【解决方案1】:

    这样的查询呢:

    SecurityPrice.objects.order_by('security', '-created').distinct('security')
    

    【讨论】:

    • 可能是,这将是一个好点,但不适用于 sqlite :( Django 引发 NotImplementedError 异常:此数据库后端不支持 DISTINCT ON 字段
    • 哦,是的。是时候切换到像 postgres 这样更严肃的数据库了吗?
    • 谢谢,也许在生产上我会听取你的建议。但是对于原型设计来说,sqlite 非常有用...
    猜你喜欢
    • 2019-09-14
    • 1970-01-01
    • 2020-09-09
    • 2021-12-13
    • 2019-11-15
    • 1970-01-01
    • 2021-01-20
    • 2012-09-09
    • 2013-07-27
    相关资源
    最近更新 更多