在 django 中选择不同的单独列?

发布于 2024-09-26 02:44:23 字数 614 浏览 6 评论 0原文

我很好奇是否有任何方法可以在 Django 中执行查询而不是下面的“SELECT * FROM...”。我正在尝试执行“SELECT DISTINCT columnName FROM ...”。

具体来说,我有一个如下所示的模型:

class ProductOrder(models.Model):
   Product  = models.CharField(max_length=20, promary_key=True)
   Category = models.CharField(max_length=30)
   Rank = models.IntegerField()

其中 RankCategory 内的排名。我希望能够迭代所有类别,对该类别中的每个排名执行一些操作。

我想首先获取系统中所有类别的列表,然后查询该类别中的所有产品并重复,直到处理完每个类别。

我宁愿避免使用原始 SQL,但如果我必须这样做,那也没关系。尽管我以前从未在 Django/Python 中编写过原始 SQL 代码。

I'm curious if there's any way to do a query in Django that's not a "SELECT * FROM..." underneath. I'm trying to do a "SELECT DISTINCT columnName FROM ..." instead.

Specifically I have a model that looks like:

class ProductOrder(models.Model):
   Product  = models.CharField(max_length=20, promary_key=True)
   Category = models.CharField(max_length=30)
   Rank = models.IntegerField()

where the Rank is a rank within a Category. I'd like to be able to iterate over all the Categories doing some operation on each rank within that category.

I'd like to first get a list of all the categories in the system and then query for all products in that category and repeat until every category is processed.

I'd rather avoid raw SQL, but if I have to go there, that'd be fine. Though I've never coded raw SQL in Django/Python before.

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

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

发布评论

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

评论(4

骑趴 2024-10-03 02:44:23

从数据库获取不同列名称列表的一种方法是使用 distinct()values()

在您的情况下,您可以执行以下操作来获取不同类别的名称:

q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.

# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"

这里需要记住一些事情。首先,这将返回一个 ValuesQuerySet,其行为与 QuerySet 不同。当您访问 q 的第一个元素(上面)时,您将获得一个字典,而不是 ProductOrder< 的实例/代码>。

其次,最好阅读警告说明 在有关使用 distinct() 的文档中。上面的示例可以工作,但 distinct()values() 的所有组合可能不会。

PS:模型中的字段使用小写名称是个好主意。在您的情况下,这意味着重写您的模型,如下所示:

class ProductOrder(models.Model):
    product  = models.CharField(max_length=20, primary_key=True)
    category = models.CharField(max_length=30)
    rank = models.IntegerField()

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values().

In your case you can do the following to get the names of distinct categories:

q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.

# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"

There are a couple of things to remember here. First, this will return a ValuesQuerySet which behaves differently from a QuerySet. When you access say, the first element of q (above) you'll get a dictionary, NOT an instance of ProductOrder.

Second, it would be a good idea to read the warning note in the docs about using distinct(). The above example will work but all combinations of distinct() and values() may not.

PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:

class ProductOrder(models.Model):
    product  = models.CharField(max_length=20, primary_key=True)
    category = models.CharField(max_length=30)
    rank = models.IntegerField()
习惯成性 2024-10-03 02:44:23

实际上很简单如果您使用 PostgreSQL,只需使用 distinct(columns) (文档)。

Productorder.objects.all().distinct('category')

请注意,该功能从 Django 1.4 起就已包含在其中

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

吃不饱 2024-10-03 02:44:23

用户使用该字段进行排序,然后进行区分。

ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()

User order by with that field, and then do distinct.

ProductOrder.objects.order_by('category').values_list('category', flat=True).distinct()
我是男神闪亮亮 2024-10-03 02:44:23

其他答案都很好,但这更干净一些,因为它只提供像从 DISTINCT 查询中获得的值一样,没有任何 Django 的缺陷。

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}

或者

>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

并且,它无需 PostgreSQL 即可工作。

这比使用 .distinct() 效率低,假设数据库中的 DISTINCT 比 python set 更快,但它非常适合围绕 shell 进行操作。

更新
这个答案非常适合在开发期间在 Django shell 中进行查询。请勿在生产中使用此解决方案,除非您绝对确定在应用 set 之前总是获得少量结果。否则,从性能的角度来看,这是一个糟糕的主意。

The other answers are fine, but this is a little cleaner, in that it only gives the values like you would get from a DISTINCT query, without any cruft from Django.

>>> set(ProductOrder.objects.values_list('category', flat=True))
{u'category1', u'category2', u'category3', u'category4'}

or

>>> list(set(ProductOrder.objects.values_list('category', flat=True)))
[u'category1', u'category2', u'category3', u'category4']

And, it works without PostgreSQL.

This is less efficient than using a .distinct(), presuming that DISTINCT in your database is faster than a python set, but it's great for noodling around the shell.

Update:
This is answer is great for making queries in the Django shell during development. DO NOT use this solution in production unless you are absolutely certain that you will always have a trivially small number of results before set is applied. Otherwise, it's a terrible idea from a performance standpoint.

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