我想运行一个查询:
从“Media”表中获取最新对象(created_at)并根据“喜欢”对其进行排序。 (请查看示例以了解“最新”的含义)
示例:
media_id - created_at - likes
media_1 - 11/03/2017 - 12
media_2 - 10/03/2017 - 13
media_1 - 06/03/2017 - 8
media_3 - 02/03/2017 - 6
在这里,我们有2次media_1,我想只保留最新的(created_at)。然后,我想通过'-likes'订购。
将返回:
media_id - created_at - likes
media_2 - 10/03/2017 - 13
media_1 - 11/03/2017 - 12
media_3 - 02/03/2017 - 6
我试图运行它,但它会抛出一条错误消息: MyQuery.order_by('media_id',' - create_at')。distinct('media_id')。order_by(' - likes')
编辑:
我不知道它有什么用,但这是我的模特:
instagram_user = models.ForeignKey(SocialAccount, on_delete=models.CASCADE)
media_id = models.TextField(null=True, blank=True)
type = models.TextField(null=True, blank=True)
link = models.TextField(null=True, blank=True)
likes = models.IntegerField()
comments = models.IntegerField()
location = JSONField(null=True, blank=True)
images = JSONField(null=True, blank=True)
videos = JSONField(null=True, blank=True)
link = models.URLField(null=True, blank=True)
tags = JSONField(null=True, blank=True)
filter = JSONField(null=True, blank=True)
caption = JSONField(null=True, blank=True)
user_has_liked = models.BooleanField(default=False)
attribution = JSONField(null=True, blank=True)
users_in_photo = JSONField(null=True, blank=True)
created_time = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.media_id
class Meta:
verbose_name_plural = "Instagram Media"
答案 0 :(得分:0)
qv = Query.objects.order_by('-created_at','-likes')[:0]
答案 1 :(得分:0)
从表格“Media”获取最新对象,并根据“喜欢”订购。
您没有声明您希望对象最新(!)
假设5天,那么:
from datetime import datetime, timedelta
now_dt = datetime.now()
before_5_days = now_dt - timedelta(days=5)
# Get from the table "Media" the latest (5 days) objects and order them based on "likes".
Media.objects.filter(created_at__lte=now_dt, created_at__gte=before_5_days).order_by('likes')