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')
我想检索所有对于code
和secondary_code
唯一的帖子(因此,在post_2
和post_3
之间只有一个,因为它们具有相同的code
和secondary_code
(,然后选择基于最古老的execution
(因此,在此(获得情况,我想要post_1
和post_2
,因为post_2
的CC_11年龄比post_3
的execution
年龄更大(。
我需要支持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, )