Django: select values with max timestamps or join to the same table

后端 未结 1 1693

I have a simple Django models

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

class ServerPropertie(models.Model):
    name = models         


        
相关标签:
1条回答
  • 2021-01-13 06:22

    if you're using PostgreSQL, usual syntax for that is:

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

    From 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.

    You can see and try it in sql fiddle demo.

    It's possible to translate this syntax to django, from django documentation:

    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.

    So in django it will be something like:

    ServerPropertie.objects.filter(...).order_by('name', '-timestamp').distinct('name')
    
    0 讨论(0)
提交回复
热议问题