Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django:不同字段的最早条目_Django_Django Models - Fatal编程技术网

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, )