从表字段中选择不同的值

发布于 2024-08-25 12:49:59 字数 461 浏览 9 评论 0原文

我正在努力理解 Django 的 ORM。我想要做的是在我的表上的字段中获取不同值的列表....相当于以下操作之一:(

SELECT DISTINCT myfieldname FROM mytable

或者)

SELECT myfieldname FROM mytable GROUP BY myfieldname

我至少想在诉诸原始方法之前以 Django 方式执行此操作sql。 例如,有一个表:

ID、街道、城市

赫尔大街 1 号

赫尔其他街 2 号

3,比布尔路,莱斯特

4,另一种方式,莱斯特

伦敦高街 5 号

我想得到:

赫尔城、莱斯特、伦迪迪姆。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

嘴硬脾气大 2024-09-01 12:49:59

假设您的模型是“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',)

由于您可能设置了 Metaordering 属性(它是元组或列表),因此您可以使用 order_by()< /code> 不带参数,可在使用 distinct() 时清除任何顺序。请参阅 order_by() 下的文档

如果您不希望对查询应用任何排序,甚至不希望使用默认排序,请调用不带参数的 order_by()。

distinct() 中该注释讨论了使用 distinct() 进行排序的问题。

要查询数据库,您只需调用:

models.Shop.objects.order_by().values('city').distinct()

它返回一个字典

models.Shop.objects.order_by().values_list('city').distinct()

此返回一个 ValuesListQuerySet,您可以将其转换为 list
您还可以将 flat=True 添加到 values_list 来展平结果。

另请参阅:按字段获取查询集的不同值

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 (which is tuple or a list), 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()

It returns a dictionary

or

models.Shop.objects.order_by().values_list('city').distinct()

This one returns a ValuesListQuerySet which you can cast to a list.
You can also add flat=True to values_list to flatten the results.

See also: Get distinct values of Queryset by field

守护在此方 2024-09-01 12:49:59

除了仍然非常相关的 jujule 的答案之外,我发现了解 order_by() on distinct("field_name") 查询。 但是,这是 Postgres 特有的功能!

如果您使用 Postgres 并且定义了一个查询应该不同的字段名称,那么 order_by() 需要以相同的字段名称(或多个字段名称)以相同的顺序开始(之后可能有更多字段)。

注意

指定字段名称时,必须在字段中提供 order_by()
QuerySet,order_by() 中的字段必须以
unique(),顺序相同。

例如,SELECT DISTINCT ON (a) 为您提供每个的第一行
a 列中的值。如果您不指定订单,您会得到一些
任意行。

例如,如果您想提取您知道的商店所在的城市列表,则 jujule 的示例必须适应于此:

# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')  

In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by() on distinct("field_name") queries. This is, however, a Postgres only feature!

If you are using Postgres and if you define a field name that the query should be distinct for, then order_by() needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).

Note

When you specify field names, you must provide an order_by() in the
QuerySet, and the fields in order_by() must start with the fields in
distinct(), in the same order.

For example, SELECT DISTINCT ON (a) gives you the first row for each
value in column a. If you don’t specify an order, you’ll get some
arbitrary row.

If you want to e.g. extract a list of cities that you know shops in, the example of jujule would have to be adapted to this:

# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')  
悲歌长辞 2024-09-01 12:49:59

举例来说:

# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []

By example:

# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []
压抑⊿情绪 2024-09-01 12:49:59

SELECT DISTINCT 语句用于仅返回不同(不同)的值。在表中,一列通常包含许多重复值;使用 distinct() 我们可以获得唯一数据。

event = Event.objects.values('item_event_type').distinct()
序列化器= ItemEventTypeSerializer(事件,许多= True)
返回响应(serializer.data)

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; using distinct() we can get Unique data.

event = Event.objects.values('item_event_type').distinct()
serializer= ItemEventTypeSerializer(event,many=True)
return Response(serializer.data)

薄荷梦 2024-09-01 12:49:59

如果您使用PostgreSQL并且您只想获取并仅使用一个特定字段进行区分,您可以使用

MyModel.objects.values('name').annotate(Count('id')).order_by()

此查询集返回其“名称”字段是唯一的行通过具有相同名称的行数,

<QuerySet [{'name': 'a', 'id__count': 2}, {'name': 'b', 'id__count': 2}, {'name': 'c', 'id__count': 3}>

我知道返回的数据不完整,有时不令人满意,但有时很有用

文档参考

If you don't use PostgreSQL and you just want to get and distinct with only one specific field you can use

MyModel.objects.values('name').annotate(Count('id')).order_by()

this queryset return us rows that their 'name' field is unique with the count of the rows that have same name

<QuerySet [{'name': 'a', 'id__count': 2}, {'name': 'b', 'id__count': 2}, {'name': 'c', 'id__count': 3}>

I know the returned data is not complete and sometimes is not satisfying but sometimes it's useful

document reference

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文