Django:不同字段的最早条目
我有以下模型(出于示例目的简化): 在数据库上,我有以下实例:Django:不同字段的最早条目,django,django-models,Django,Django Models,我有以下模型(出于示例目的简化): 在数据库上,我有以下实例: 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 = Po
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')
我想检索所有帖子,对于code
和secondary\u code
(因此,只有post\u 2
和post\u 3
之间的帖子是唯一的,因为它们具有相同的code
和secondary\u code
),并根据最早的执行情况选择要获取的帖子(因此,在这种情况下,我想要post_1
和post_2
,因为post_2
的执行时间比post_3
的执行时间要长)
我需要同时支持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, )
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, )