是否可以通过django-nonrel / Google App Engine中的主键获取对象?

时间:2022-05-18 23:09:51

I'm trying to retrieve a model object like the code below:

我正在尝试检索模型对象,如下面的代码:

(r'^album/(?P<album_id>\w+)/$', 'core.views.album'),

def album(request, album_id):
    album = Album.objects.get(pk=album_id)

The problem is that the PK is not an integer:

问题是PK不是整数:

>>> a = Album.objects.all()[0]
>>> a.pk
46L

The error I'm getting when I run the view:

我运行视图时遇到的错误:

ValueError at /album/46L/
invalid literal for int() with base 10: '46L'

Ideas? Thanks.

2 个解决方案

#1


1  

46L is a long integer, not a string, so you should treat it as a number and not a word in urls.py:

46L是一个长整数,而不是一个字符串,所以你应该把它当作数字而不是urls.py中的单词:

(r'^album/(?P<album_id>\d+)/$', 'core.views.album'),

then the url /album/46/ will end up calling:

然后url / album / 46 /将最终调用:

def album(request, album_id):
    #album = Album.objects.get(pk=46L)
    album = Album.objects.get(pk=album_id)

Or if you need to keep the 'L' in the url for some reason, cast it as a long before using it:

或者,如果由于某种原因需要在网址中保留“L”,请在使用之前将其投放一段时间:

album = Album.objects.get(pk=long(album_id))

#2


0  

The problem was unrelated with the urls / views. Everytime I executed "runserver" my local datastore was being erased. So the data I was able to retrieve when using "shell" was not synced correctly.

这个问题与网址/观点无关。每次我执行“runserver”时,我的本地数据存储区都被删除了。因此,使用“shell”时我能够检索的数据未正确同步。

This happened because, for some weird reason, I commented this line (and forgot about it) on settings.py:

发生这种情况是因为,出于一些奇怪的原因,我在settings.py上评论了这一行(并忘了它):

AUTOLOAD_SITECONF = 'indexes'

#1


1  

46L is a long integer, not a string, so you should treat it as a number and not a word in urls.py:

46L是一个长整数,而不是一个字符串,所以你应该把它当作数字而不是urls.py中的单词:

(r'^album/(?P<album_id>\d+)/$', 'core.views.album'),

then the url /album/46/ will end up calling:

然后url / album / 46 /将最终调用:

def album(request, album_id):
    #album = Album.objects.get(pk=46L)
    album = Album.objects.get(pk=album_id)

Or if you need to keep the 'L' in the url for some reason, cast it as a long before using it:

或者,如果由于某种原因需要在网址中保留“L”,请在使用之前将其投放一段时间:

album = Album.objects.get(pk=long(album_id))

#2


0  

The problem was unrelated with the urls / views. Everytime I executed "runserver" my local datastore was being erased. So the data I was able to retrieve when using "shell" was not synced correctly.

这个问题与网址/观点无关。每次我执行“runserver”时,我的本地数据存储区都被删除了。因此,使用“shell”时我能够检索的数据未正确同步。

This happened because, for some weird reason, I commented this line (and forgot about it) on settings.py:

发生这种情况是因为,出于一些奇怪的原因,我在settings.py上评论了这一行(并忘了它):

AUTOLOAD_SITECONF = 'indexes'