Django:选择具有最大时间戳的值或连接到同一个选项卡

2024-09-29 19:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的Django模型

class Server(models.Model):
    name = models.CharField(max_length=120)

class ServerPropertie(models.Model):
    name = models.CharField(max_length=120)
    value = models.CharField(max_length=120)
    timestamp = models.DateTimeField()
    server = models.ForeignKey(Server)

我想将get_properties方法添加到服务器模型中,它将返回当前服务器的所有最后属性。我的意思是,它应该返回当前服务器的所有属性名的名称和值,并且每个uniq属性名都应该有一个值,该行有一个最大时间戳。在

我可以用原始硬编码的原始SQL(我使用postgres):

^{pr2}$

或者在python中,但是我相信存在python解决方案。你能帮帮我吗。在


Tags: djangoname模型服务器model属性servervalue
1条回答
网友
1楼 · 发布于 2024-09-29 19:30:26

如果使用的是PostgreSQL,通常的语法是:

select distinct on (name)
    name, value
from environments_serverpropertie
where server = ...
order by name, timestamp desc

来自PostgreSQL documentation

SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first.

你可以在sql fiddle demo中看到并尝试它。在

可以将此语法从django documentation转换为django:

On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply. This translates to a SELECT DISTINCT ON SQL query.

因此,在django,它将类似于:

^{pr2}$

相关问题 更多 >

    热门问题