我有 2 個模型:
models.py
class Post(models.Model):
title = models.CharField(max_length=255)
desc = models.CharField(max_length=500)
content = models.TextField()
uploadedBy = models.ForeignKey(User, on_delete=models.CASCADE)
LIKE_CATEGORIES = (
("LIKE", "LIKE"),
("DISLIKE", "DISLIKE")
)
class PostLike(models.Model):
_type = models.CharField(max_length=200, choices=LIKE_CATEGORIES, blank=True, null=True)
content = models.ForeignKey(
Post, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
我想Post根據帖子的點贊數進行排序。一個帖子的點贊數是擁有 的PostLike物件的數量_type="LIKE",content=post_object。
如何Post根據喜歡的數量專門訂購?
uj5u.com熱心網友回復:
您可以使用相關 PostLike 物件的計數來注釋每個 Post ,這可以有一個過濾器來僅計算滿足條件的相關物件。然后按注解排序
from django.db.models import Count, Q
Post.objects.annotate(
likes=Count('postlike', filter=Q(postlike___type="LIKE"))
).order_by('-likes')
我不確定有一個帶有下劃線前綴的欄位是最好的主意,它可能會弄亂 ORM 和 Django 內部的其他部分
uj5u.com熱心網友回復:
這會將您的過濾器限制為使用 LIKE 發布并對其進行排名
from django.db.models import Count
Post.objects.filter(postlike___type='LIKE').annotate(likes=Count('postlike')).order_by('-likes')
Or
from django.db.models import Count
Post.objects.filter(postlike___type='LIKE').annotate(Count('postlike'))[::-1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361123.html
