model类如下,我在class Meta中设置了ordering = ['-date_create'],即模型对象返回的记录结果集是按照这个字段排序的。
class SystemUserPushHistory(models.Model):
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
host_name = models.CharField(max_length=128, null=False)
system_username = models.CharField(max_length=128, null=False)
method = models.CharField(max_length=32, null=False)
is_success = models.BooleanField(default=False)
date_create = models.DateTimeField(auto_now_add=True, editable=False)
message = models.CharField(max_length=4096, null=True)
class Meta:
db_table = "assets_systemuser_push_history"
ordering = ['-date_create']
def __str__(self):
ret = self.system_username + " => " + self.host_name
return ret
当业务有需求如对host_name进行分组显示,在代码中用到了annotate,如下。
>>> from django.db.models import Count
>>> from assets.models import SystemUserPushHistory
>>> p = SystemUserPushHistory.objects.values("host_name").annotate(dcount=Count(1))
>>> p
>>> print(p.query)
SELECT `assets_systemuser_push_history`.`host_name`, COUNT(1) AS `dcount` FROM `assets_systemuser_push_history` GROUP BY `assets_systemuser_push_history`.`host_name`, `assets_systemuser_push_history`.`date_create` ORDER BY `assets_systemuser_push_history`.`date_create` DESC
可以看到,所得到的结果并不像我们预期的一样,之后把执行的sql输出出来可以看到在group by的时候是对host_name和date_create进行分组,原因就是因为我们在model类中设置了ordering,去掉之后代码运行正常。
使用distinct和上面的情况类似,就不列出来了。