如何在Django中通过列值过滤多行到单行?



我有一个通知模型:

class Notification(models.Model):
class VerbChoices(models.TextChoices):
COMMENTED = 'commented'
LIKE = 'like'
id = models.CharField(primary_key=True, default=generate_id, max_length=255)
actor = models.ForeignKey(Users, on_delete=models.DO_NOTHING, related_name='notify_actions', null=True)
recipient = models.ForeignKey(Users, on_delete=models.DO_NOTHING, related_name='notifications')
verb = models.CharField(max_length=255, choices=VerbChoices.choices)
read = models.BooleanField(default=False)
target_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
target_object_id = models.CharField(max_length=255)
target = GenericForeignKey('target_content_type', 'target_object_id')
created_at = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)

我正试图编写一个查询,该查询将返回verb= LIKE的行数,按target_object_id分组。

期望的响应示例:

[
{
"id": "lokv7s1ljjarp9",
"actor": {},
"recipient": {},
"verb": "commented",
"read": true,
"target": {
"id": "5cj9kxbih6tbl7",
},

},
{
"id": "kaevq7mrsbvx4f",
"actor": {},
"recipient": {},
"verb": "commented",
"read": true,
"target": {
"id": "5cj9kxbih6tbl7",
},
},
{
"id": "jhoonpbu8m5p43",
"actor": {<id of the first actor in the list>},
"recipient": {},
"verb": "liked",
"read": "true if one of the records is unread",
"target": {
"id": "5cj9kxbih6tbl7",
},
"count": "total number of likes"
}
]

注意对同一目标的评论有不同的回复,并且点赞在一个回复中。

你可以试试这个选项

Notifications.objects.all () .annotate (target_objects = Count("作者"))

最新更新