Django:不同字段的最古老的入口



i具有以下模型(用于示例目的(:

class Execution(models.Model):
    name = models.CharField(null=False, max_length=30)
    creation_date = models.DateTimeField(auto_now_add=True, null=False)
class Post(models.Model):
    class Meta:
        unique_together = ('code', 'secondary_code', 'execution')
    code = models.CharField(null=False, max_length=30)
    secondary_code = models.CharField(null=False, max_length=3)
    execution = models.ForeignKey(Execution, null=False, on_delete=models.CASCADE)
    text = models.TextField()

在数据库上我有以下实例:

execution_1 = Execution('Execution 1', '2019-01-01')
execution_2 = Execution('Execution 2', '2019-01-02')
post_1 = Post('123', '456', execution_1, 'lorem')
post_2 = Post('789', '999', execution_1, 'ipsum')
post_3 = Post('789', '999', execution_2, 'dolor')

我想检索所有对于codesecondary_code唯一的帖子(因此,在post_2post_3之间只有一个,因为它们具有相同的codesecondary_code(,然后选择基于最古老的execution(因此,在此(获得情况,我想要post_1post_2,因为post_2的CC_11年龄比post_3execution年龄更大(。

我需要支持Postgres和Sqlite3 3.18.0,因此,由于SQLITE,我无法使用窗口函数。

如何做?

newer_post = Post.objects.filter(code=OuterRef('code'), 
    secondary_code=OuterRef('secondary_code'), 
    execution__creation_date__gt=OuterRef('execution_dt'), 
)
posts = Post.objects.all().annotate(execution_dt=execution__creation_date, )
latest_posts = posts.
    annotate(has_newer_post=Exists(newer_post), ).
    filter(has_newer_post=False, )

最新更新