我有一个用于近距离搜索的地理对象。该对象通过各种路径被键控到不同的其他对象。
示例:
blog.geo_object
user.profile.geo_object
group.event.geo_object
现在,我做了一个边界框搜索,它的字符串如下:
radius_queryset = base_queryset.filter(
user__profile__geo__lat__gte = bounding_box.lat_min,
user__profile__geo__lat__lte = bounding_box.lat_max,
user__profile__geo__lon__gte = bounding_box.lon_min,
user__profile__geo__lon__lte = bounding_box.lon_max,
然后在其他对象上:
radius_queryset = base_queryset.filter(
blog__geo__lat__gte = bounding_box.lat_min,
blog__geo__lat__lte = bounding_box.lat_max,
blog__geo__lon__gte = bounding_box.lon_min,
blog__geo__lon__lte = bounding_box.lon_max,
)
它遵循以下的一般格式:
radius_queryset = base_queryset.filter(
[lookup_path]__geo__lat__gte = bounding_box.lat_min,
[lookup_path]__geo__lat__lte = bounding_box.lat_max,
[lookup_path]__geo__lon__gte = bounding_box.lon_min,
[lookup_path]__geo__lon__lte = bounding_box.lon_max,
)
# where lookup_path = "blog" or "user__profile" in the two above examples
我正在编写足够多的这些(到目前为止,还会有更多)来泛化查询--封装是可维护性的好朋友,也是与拼写错误作斗争的盟友。
那么,对于我的问题:除了使用exec和eval (看起来很丑陋)之外,有没有一种方法可以在变量中将筛选器参数名称转换为sub?我是不是漏掉了什么简单的东西?
发布于 2012-01-20 05:20:31
**kwargs
就是你的答案!
def generate_qs(lookup_path, bounding_box):
return base_queryset.filter(**{
lookup_path + '__geo__lat__gte' : bounding_box.lat_min,
lookup_path + '__geo__lat__lte' : bounding_box.lat_max,
lookup_path + '__geo__lon__gte' : bounding_box.lon_min,
lookup_path + '__geo__lon__lte' : bounding_box.lon_max,
})
radius_queryset = generate_qs('blog', bounding_box)
发布于 2012-01-20 05:24:35
我认为您可以使用Python语言的**kwargs
语法在一个辅助函数中消除这种混乱。类似于:
def helper(lookup_path, bounding_box):
return dict([ ("%s__geo__%s" % (lookup_path, lkup_left, ),
getattr(bounding_box, lkup_right), )
for lkup_left, lkup_right in
(("lat__gte", "lat_min", ),
("lat__lte", "lat_max", ),
("lon__gte", "lon_min", ),
("lon__lte", "lon_max", ),
) ])
qs = base_queryset.filter(**helper(lookup_path, bounding_box))
https://stackoverflow.com/questions/8933313
复制相似问题