0

我有以下模型:

class ProjectRecord(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True,related_name='user_projects')
    project = models.ForeignKey(Project,on_delete=models.CASCADE, null=True, blank=True, related_name='user_projects')
    project_type = models.CharField(max_length=30, choices=(("project_a","A"),("project_b","B")),null=True)
    version = models.FloatField(null=True, blank=True)

我想用这个过滤版本的最新值:

project = list(ProjectRecord.objects.filter(
    user=self.request.user, project_type='project_a'
))

但我不知道如何实现它。数据库中的数据类似如下:

id project_id version project_type
1   5          1.0      project_a
2   5          1.0      project_b
3   4          1.0      project_a
4   4          1.0      project_b
5   5          2.0      project_a          
6   5          2.0      project_b
7   5          3.0      project_a
8   5          3.0      project_b

例如,我想获取的最新值project_id=5与其他数据完全匹配,并且project_id如果他们的版本没有更新,则不要删除其他的值,queryset应该显示如下

id project_id version project_type
1   4          1.0      project_a
2   4          1.0      project_b
3   5          3.0      project_a
4   5          3.0      project_b
4

1 回答 1

1

尝试使用注释Max

from django.db.models import Max

ProjectRecord.objects.filter(
    user=self.request.user,
    project_type='project_a'
).values(
    'project_id', 'project_type'
).annotate(
    max_version=Max('version')
)
于 2018-06-09T08:22:53.813 回答