Django:如何按时间戳对查询集进行分组

时间:2021-05-11 10:47:27

标签: python django django-models

我有这两个模型

class Blog(models.Model):
    title = models.CharField(unique=True, max_length=255)
class Tag(models.Model):
    blog = models.ForeignKey(Blog)
    tag = models.CharField(max_length=255)
    timestamp = models.DateTimeField(db_index=True)

        class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["blog_id", "timestamp"],
                name="Timestamp per blog must be unique"),
        ]

假设某些博客的 ID 是 [1,2,3,4,5]

我想以结果按时间戳分组的方式查询和分组标签。 示例输出将类似于

[
 {'timestamp': '2021-04-13 15:35:26+00:00', [title_of_blog_id_1]: "hello", 'tag': 'Hello',
 [title_of_blog_id_2]: "new title", 'tag': 'new'}
 {'timestamp': '2021-04-13 15:55:26+00:00', [title_of_blog_id_1]: "hello next", 'tag': 'next',
 [title_of_blog_id_2]: "new updated title", 'tag': 'UP'}
]

输出说明:

我想要一种情况,其中标签按时间戳分组,对于每个时间戳,它获取该时间戳的所有博客标题和相应标签。

0 个答案:

没有答案
相关问题