从表字段中选择不同的值 [英] Select distinct values from a table field

查看:120
本文介绍了从表字段中选择不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django的ORM中挣扎着我的头脑。我想做的是在表的一个字段中获取不同值的列表....相当于以下之一:

  SELECT DISTINCT myfieldname FROM mytable 

(或者)

  SELECT myfieldname FROM mytable GROUP BY myfieldname 

我至少喜欢在使用原始sql之前做Django方式。
例如,一个表:


id,街道,城市



1,主街,赫尔



2,其他街,Hull



3,Bibble Way,莱斯特



4,莱斯特的另一种方式



5,High Street,Londidium


我想得到:


Hull,Leicester,Londidium



解决方案

说你的模型是店铺

  class Shop(models.Model):
street = models.CharField(max_length = 150)
city = models.CharField(max_length = 150 )

#你的某些模型可能有明确的订单
class Meta:
ordering =('city')

由于您可能有 Meta 订购属性设置,您可以使用 order_by()而无需清除任何参数使用 distinct()时的排序。请参阅 order_by ()


如果您不希望将任何顺序应用于查询,默认排序,调用order_by(),不带参数。


distinct() 在其中讨论使用问题的注释



要查询您的数据库,您只需拨打:

  models.Shop.objects.order_by()。values('city')。distinct()#返回字典

  models.Shop .objects.order_by()。values_list('city')。distinct()#返回一个元组的列表。 

您还可以将 flat = True 添加到 values_list 要有一个平面列表。



另请参见:按字段获取不同的Queryset值


I'm struggling getting my head around the Django's ORM. What I want to do is get a list of distinct values within a field on my table .... the equivalent of one of the following:

SELECT DISTINCT myfieldname FROM mytable

(or alternatively)

SELECT myfieldname FROM mytable GROUP BY myfieldname

I'd at least like to do it the Django way before resorting to raw sql. For example, with a table:

id, street, city

1, Main Street, Hull

2, Other Street, Hull

3, Bibble Way, Leicester

4, Another Way, Leicester

5, High Street, Londidium

I'd like to get:

Hull, Leicester, Londidium.

解决方案

Say your model is 'Shop'

class Shop(models.Model):
    street = models.CharField(max_length=150)
    city = models.CharField(max_length=150)

    # some of your models may have explicit ordering
    class Meta:
        ordering = ('city')

Since you may have the Meta class ordering attribute set, you can use order_by() without parameters to clear any ordering when using distinct(). See the documentation under order_by()

If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.

and distinct() in the note where it discusses issues with using distinct() with ordering.

To query your DB, you just have to call:

models.Shop.objects.order_by().values('city').distinct()  # returns a dictionary

or

models.Shop.objects.order_by().values_list('city').distinct()  # returns a list of tuples.

You can also add flat=True to values_list to have a flat list.

See also: Get distinct values of Queryset by field

这篇关于从表字段中选择不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆