【发布时间】:2012-12-29 01:09:18
【问题描述】:
我目前正在编写一个项目,该项目在后端使用带有 Django-Rest-Framework 的 Django,在前端使用 Ember.js/Ember-data。
我希望以这种格式将查询从我的 ember 应用程序传递回我的 django api
http://myurl.com/application/api/model/?parameter=X
其中参数是正在查询的模型上的一个字段,X 是要搜索的值。
像这样松散的东西应该是结果查询
queryset = Model.objects.filter(**request.QUERY_PARAMS.dict())
其中 QUERY_PARAMS.dict() 是给出格式字典的 Django 语法
{parameter:X}
** 将 dict 转换为 Django 所期望的关键字参数。
因此上面的行是有效的:
queryset = Model.objects.filter(parameter=X)
我已经使用自定义视图和自定义 mixin 进行了这项工作,但我担心我的查询处理实现可能有点幼稚,这让我觉得这是一种非常常见的模式。
我想知道是否有针对 Django 的库,或者我不完全理解的一些 Django 内部组件可以在没有我的自定义查询集代码的情况下为我处理这些相对常见的查询?
任何正确方向的指点将不胜感激。
史蒂夫·凯恩
编辑:
def get_integer_queryset(self, query, queryset):
#stringify the first entry in query.keys (query is request.QUERY_PARAMS)
query_key = str(query.keys()[0])
#split the string into individual strings since the request object dict
#contains only a string of numbers and not an actual array (see below)
#query = {'parameter':'1,2,3,4'} becomes {'parameter':['1','2','3','4']}
query_values = query.get(query_key, None).split(",")
#construct two dicts. One handles integers and the other handles "null"
#all the code below is required because Django does not seem to handle "null"
#as a valid query to a field that is type "integer"
#as a side note, I think this is poor and create annoying work...i would love
#to be wrong here
#the Q objects are required in order to compose a query of both integers and
#the string "null"
query_vals_no_null = {query_key+"__in": []}
optional_null_dict = {}
for value in query_values:
if value == "null" or value == "None":
optional_null_dict[query_key+"__isnull"] = True
else:
query_vals_no_null[query_key+"__in"].append(value)
return queryset.filter( Q(**query_vals_no_null) |
Q(**optional_null_dict) )
这是我从处理整数查询的自定义视图中获取的主要方法。我插入了 cmets 以澄清正在发生的事情。让我知道这是否有帮助或看起来很熟悉/可怕/真棒/有点温和。
史蒂夫
【问题讨论】:
-
这类似于 django 的旧管理文件系统。但最近,他们添加了验证以确保只能查询特定参数。您可能对此感兴趣,也可能不感兴趣(只需将输入与 VALID_PARAM_KEYS 列表进行比较)。
-
Steve django-rest-framework 社区似乎生活在 google 组而不是 stackoverflow 上(无论好坏)。我还没有像你上面提到的那样做任何自定义查询逻辑,但我想在你得到一个可靠的后端答案后跟进,因为我刚刚完成了 django-rest-framework 的 v1.0 ember-data 适配器和这个似乎是必须具备的功能。 groups.google.com/forum/?fromgroups#!forum/…
-
我从我的视图中添加了一个方法 sn-p 来展示我处理查询的方法。此方法仅适用于针对“整数”类型字段的查询。它也适用于相关字段,前提是相关字段的引用是整数(通常是 PK)。
标签: django ember.js django-views django-rest-framework