Django model get unique foreign key rows based on other column max value -
i'm new django, , i'm trying create simple application keep track on different server configurations in sqlite database. i've created 2 database models:
from django.db import models class server(models.model): name = models.charfield(max_length=250) class config(models.model): server = models.foreignkey(server, on_delete=models.cascade) configuration = models.charfield(max_length=250) config_version = models.integerfield()
here 2 models sample data:
server: | id | name | | ------ | ------ | | 1 | server1 | | 2 | server2 | | 3 | server3 | config: | id | configuration | config_version | server | | ------ | ------------- | -------------- | ------ | | 1 | srv1_cfg1 | 1 | 1 | | 2 | srv2_cfg1 | 1 | 2 | | 3 | srv2_cfg2 | 2 | 2 | | 4 | srv2_cfg3 | 3 | 2 | | 5 | srv3_cfg1 | 1 | 3 | | 6 | srv1_cfg2 | 2 | 1 | | 7 | srv1_cfg3 | 3 | 1 |
i query config table, , rows maximum value of "config_version" field each server id, like:
desired result: | id | configuration | config_version | serverid | servername | | ------ | ------------- | -------------- | -------- | ---------- | | 4 | srv2_cfg3 | 3 | 2 | server2 | | 5 | srv3_cfg1 | 1 | 3 | server3 | | 7 | srv1_cfg3 | 3 | 1 | server1 |
i've tried many different options construct correct query, far cannot want. best result query server table:
server.objects.annotate(maxver=max('config__config_version'))
but seems cannot access config table objects, guess need query config table filtering?
i can raw sql query, prefer "django" way. appreciated.
after more struggle this, i've came solution works me. i'm sure not optimal, @ least seems works:
from django.db.models import max, f s1 = config.objects.annotate(maxver=max('server__config__config_version')) config_list = s1.filter(config_version=f('maxver'))
if there better way this, love know it.
Comments
Post a Comment