【问题标题】:Django: Using .distinct() on a query causes invalid DB queryDjango:在查询上使用 .distinct() 会导致无效的数据库查询
【发布时间】:2010-11-12 14:49:39
【问题描述】:

我正在尝试获取提交列表中不同商店名称的列表。

我非常简单的 Django 模型:

class Submission(models.Model):  
    title = models.CharField(max_length=50, null=True, blank=True)  
    description = models.CharField(max_length=200, null= True, blank=True)  
    store_name = models.CharField(max_length=200)  

如果我这样做:
stores = Submission.objects.values_list('store_name', flat=True)
那么打印出来的结果就好了:
[u'amazon.com', u'amazon.com', u'amazon.com', u'buy.com']

但是 - 如果我将 .distinct() 添加到查询中,则会得到 数据库不支持此查询。

关于为什么会发生这种情况的任何想法?我玩过使用 values 而不是 valueslist 没有运气。

(最新的 django 版本,Python 2.6,OS X,Google App Engine)

【问题讨论】:

  • 为了减轻问题,您可以运行 print stores.query 并在此处发布原始 sql 输出!
  • 从 app_submission 中选择不同的 app_submission.store_name

标签: django google-app-engine django-models


【解决方案1】:

Google Appengine Datastore API 不支持 distinct 功能。这就是你得到的错误所说的,所以你不能这样做。

您所能做的就是在获取这样的结果后过滤非唯一问题:

stores = Submission.objects.values_list('store_name', flat=True)
unique_stores = []
for store in stores:
    if store not in unique_stores:
        unique_stores.append(store)

【讨论】:

猜你喜欢
  • 2011-11-26
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 2018-03-11
  • 2018-03-03
  • 1970-01-01
相关资源
最近更新 更多