以下查询执行我想要它做的事情,但是,我不知道它是否有效.我浏览了Django聚合文档,将它放在一起,查看了查询,并像混淆的狗一样向侧面倾斜.
查询实际执行的操作是获取已发布的条目"名称"和"name_slug",其中包含一个或多个已批准的注释,并按最新注释的"date_published"字段对结果进行排序.结果是最近活跃的Entry的列表.
所以几个问题.(1)你在查询中看到的只是一个普通的禁忌.(2)有没有办法可以看到查询数据库的RAW SQL?
楷模:
class Entry(models.Model): name = models.CharField(max_length=200, unique=True) name_slug = models.SlugField(max_length=200, blank=True, editable=False, unique=True) date_published = models.DateTimeField() is_published = models.BooleanField(default=False) class Comment(models.Model): entry = models.ForeignKey('Entry') date_published = models.DateTimeField() approved_choices = (('N', 'No'), ('Y', 'Yes'), ('M', 'Needs Moderation'),) approved = models.CharField(max_length=1, choices=approved_choices, default='N')
查询:
active_entry_list = Entry.objects .values('name', 'name_slug') .filter(is_published=True, comment__approved='Y') .annotate(latest_comment=Max('comment__date_published'),comments=Count('comment')) .filter(comments__gte=1) .order_by('-latest_comment') [:6]
edgars.. 5
2)是的,如果settings.DEBUG为true,则原始sql查询存储在django.db.connection.queries中.
http://blog.michaeltrier.com/2007/8/11/display-the-sql-django-orm-is-generating
2)是的,如果settings.DEBUG为true,则原始sql查询存储在django.db.connection.queries中.
http://blog.michaeltrier.com/2007/8/11/display-the-sql-django-orm-is-generating