我正在尝试在 postgresql 数据库中进行查询。 我需要在查询之前将 id 乘以 -1。
def getRelation(request,id):
#id = id * -1
#osmObject = get_object_or_404(PlanetOsmPolygon,osm_id=int(id))
return HttpResponse(id)
#return HttpResponse(osmObject.way.geojson)
这是我的观点。 这段代码可以工作,但是,如果我取消注释乘法,我的浏览器中就没有任何内容。我看不到我的否定 ID。哪里错了?
如果我取消注释get_object_404
,我会得到一个:
invalid literal for int() with base 10: ''
这就是我尝试 int()
的原因。
这个问题看起来很简单,但我不明白为什么。我从 django 开始。
谢谢
最佳答案
从 url 捕获的参数(此处为您的 id
)作为字符串注入(inject)
在开始使用它之前需要强制它
类似的东西
def getRelation(request, id):
id = int(id)
# the rest of your view
更新(回复:空白字符串)
Python 允许您通过重载乘法运算符来重复字符串
>>> "foo" * 3
'foofoofoo'
当您尝试将字符串(包含您的 ID,但作为字符串)与 -1
相乘时,您会得到“-1 个副本”,这会返回一个空字符串
>>> "foo" * -1
''
或者根据您的情况:
>>> "12" * -1
''
>>> int("12") * -1
-12
关于python - Django 中的负整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635735/