如何获取一个字段的最新值(Django Model.objects.filter())

How to get the latest value of one filed(Django Model.objects.filter())

我有以下型号:

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')),但我不知道如何实现it.the数据库中的数据类似于以下内容:

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的版本未更新,则不删除其值,查询集应该是显示如下

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

非常感谢您的建议和帮助。

你可以 order_by('version') 然后获取最新的对象并观察第二个对象是否具有相同的版本。所以你把它和第三个...

试试这个,

from django.db.models import Max

queryset = ProjectRecord.objects.filter(user=self.request.user, project_type='project_a')
max_version = queryset.aggregate(max=Max('version')).get('max')
required_queryset = queryset.filter(version=max_version)


我不确定性能如何,但这肯定有效

或者你可以试试这个:

from django.db.models import Max

queryset = ProjectRecord.objects.filter(user=self.request.user) \
                                .values('project_id', 'project_type') \
                                .annotate(max_version=Max('version')