django models的values() 与 distinct()同时使用时,两者不分先后顺序 在django models中取得一个字段的distinct值

在django models中取得一个字段的distinct值

https://blog.csdn.net/tsbob/article/details/1340293

就是select distinct xxx  from table_name ...这样的功能

很简单,代码如下

xxxx.objects.values("field_name").distinct()
#或者
xxxx.objects.distinct().values("field_name") 

这两句实际生成的sql都一样。django 的models框架,看起来算是半个O/R mapping框架,相比我以前也用过hibernate,功能并不差,

一开始我怀疑上面说的这点,因为看django文档原文写了:

When using values() together with distinct(), be aware thatordering can affect the results. See the note in distinct() fordetails.

The moral here is that if you are using distinct() be careful aboutordering by related models. Similarly, when using distinct() andvalues() together, be careful when ordering by fields not in thevalues() call.

——https://docs.djangoproject.com/en/1.11/ref/models/querysets/#distinct


实际上,因为英语水平有限,我没看出来这两个地方讲的不完全是distinct()values()两者的关系,而是distinct()values() order_by()三者的关系,

大意是:当同时使用distinct()和values()时,排序(ordering)将会对结果产生影响。其实主要是distinct()与order_by()之间互相影响。


我在django文档原文中,没有找到distinct()与values()顺序对查询结果的影响的直接说明,但有一段话:

Finally, note that you can call filter(), order_by(), etc. after thevalues() call, that means that these two calls are identical:

Blog.objects.values().order_by('id')
Blog.objects.order_by('id').values()

The people who made Django prefer to put all the SQL-affecting methods first,followed (optionally) by any output-affecting methods (such as values()),but it doesn’t really matter. This is your chance to really flaunt yourindividualism.

在第一句话中,原文举了两个例子 filter(), order_by(),etc,这两个函数与values()共同使用时,顺序不分先后。后来注意到,原文中的etc是等等的意思,我猜想:distinct()就应该属于“等等”中的一个。


猜你喜欢

转载自blog.csdn.net/qq_27361945/article/details/80256298