Django query for latest version of a object

问题: I am trying to write a query in Django but I'm not sure whats the best way to write this. Also assuming that the database is mySQL. This matters if distinct is used. cl...

问题:

I am trying to write a query in Django but I'm not sure whats the best way to write this. Also assuming that the database is mySQL. This matters if distinct is used.

  class Homework(models.Model):
    title = TextField()


  class Assignment(models.Model):
      homework_id = Foreignkey(Homework, on_delete=models.CASCADE)
      task = IntegerField(default=1)
      version = IntegerField(default=1)

Given the models above I want to get all the assignments in a particular homework where the assignments are the latest version of the task. example:

Homework_id: 1
    assignment v1, t1
    assignment v2, t1
    assignment v1, t2

If I have one homework object where the assignment with task 1 and assignment task 2 are in it then the result query should return Assignment t1, v2 and Assignment t2, v1

v refers to version
t refers to task

回答1:

You could try annotating the tasks with the max version number like this:

Assignment.objects.filter(homework_id=1).values('task').annotate(version=Max('version'))

Which would get you something like:

<QuerySet [{'task': 1, 'version': 2}, {'task': 2, 'version': 1}]>
  • 发表于 2019-03-22 22:38
  • 阅读 ( 206 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除