开发者

Django: making raw SQL query, passing multiple/repeated params?

Hopefully this should be a fairly straightforward question, I just do开发者_开发技巧n't know enough about Python and Django to answer it.

I've got a raw SQL query in Django that takes six different parameters, the first two of which (centreLat and centreLng) are each repeated:

query = "SELECT units, (SQRT(((lat-%s)*(lat-%s)) + ((lng-%s)*(lng-%s)))) AS distance FROM places WHERE lat<%s AND lat>%s AND lon<%s AND lon>%s ORDER BY distance;"
params = [centreLat,centreLng,swLat,neLat,swLng,neLng]
places = Place.objects.raw(query, params)

How do I structure the params object and the query string so they know which parameters to repeat and where?


You have (at least) two options. You could either include those repeated parameters in your list in the order that they need to appear - meaning that you would end up with the same values in your list multiple times like this:

params = [centreLat,centreLng,swLat,neLat,swLng,neLng,centreLat,centreLng]

OR, you could name each parameter using a dictionary and instead of using just a "%s" you could use "%(name)s" like this:

query = "SELECT units, (SQRT(((lat-%(lat)s)*(lat-%(lat)s)) + ((lng-%(lng)s)*(lng-%(lng)s)))) AS distance FROM places WHERE lat<%(lat)s AND lat>%(lat)s AND lon<%(lng)s AND lon>%(lng)s ORDER BY distance;"
params = {'lat':centreLat,'lng':centreLng}

(don't copy that code verbatim, i'm sure that's not EXACTLY what you need)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜