如何使用ORM等效于SQL计数,分组和联接查询? [英] How to use the ORM for the equivalent of a SQL count, group and join query?
问题描述
我有可以与图像和位置相关联的标签。
I have tags which can be associated with images and locations.
- 标签是唯一的。
- 图像和位置可以有很多标签。
- 使用Tag_Item模型将所有内容链接在一起。
这里是模型:
LOCATIONS = (
('US', 'USA'),
('UK', 'United Kingdom'),
('FR', 'France'),
)
class Location(models.Model):
location = models.CharField(choices=LOCATIONS)
class Image(models.Model):
image = models.ImageField(verbose_name='Image')
class Tag(models.Model):
tag = models.CharField(max_length=150, unique=True)
class Tag_Item(models.Model):
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
location = models.ForeignKey(Location, null=True, blank=True, default=None)
image = models.ForeignKey(Image, null=True, blank=True, default=None)
created_at = models.DateTimeField(auto_now_add=True)
我想写一个查询,表示选择美国五个最常用的标签。
I want to write a query which means select the five most frequent tags for USA.
我在考虑以下SQL代码:
I was thinking something along the following lines in SQL:
- 加入标签,Tag_Item和位置为美国的位置。
- 按标签分组。
- 按Tag_ID(或类似的代码)的顺序对其进行排序。
但我不知道如何转移
您能帮我如何编写这种复杂的关系查询吗?
Can you please help me on how to write that sort of complex relationship queries?
推荐答案
您将需要一些东西来开始这样的查询:
You will need a few things to begin a query like this:
-
annotate()
,将用于执行和添加计数字段。 -
order_by()
,将用于对查询集进行排序。 -
values()
,将用于检索表的特定列。 - 关于
GROUP BY ... COUNT
的注释:
如何要在Django ORM中执行GROUP BY ... COUNT或SUM? - 您可以使用
__
标记。
annotate()
, will be used to perform and add the count field.order_by()
, will be used to order the queryset.values()
, will be used to retrieve a specific column of the table.- Notes on
GROUP BY ... COUNT
: How to execute a GROUP BY ... COUNT or SUM in Django ORM? - You can get the related field of a foreign key with the
__
notation.
您可以简化描述的查询:
You can simplify your described query:
from django.db.models import Count
usa_tags = Tag_Item.objects.filter(location__location='US')
.values('tag__tag__id')
.annotate(my_count=Count('tag__tag__id')
.order_by('my_count')
这将返回一个有序字典,该字典的第一个条目是顶部标签,第二个条目是正在使用的第二个标签,等等:
That will return an ordered dictionary who's 1st entry is the top tag 2nd entry is the second tag in use etc. :
tag_id | my_count
-------|---------
5 | 101
1 | 53
... | ...
现在,您可以从该词典中检索五个顶部标签。
Now you can retrieve the five top tags from that dictionary.
这篇关于如何使用ORM等效于SQL计数,分组和联接查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!