首页 > python > 在Django中通过id获取对象

在Django中通过id获取对象 (Getting Objects by id in Django)

问题

我想在我的django应用程序中通过id获取数据。问题是我不知道用户点击的id类型。我尝试在我的视图中添加以下代码,但我收到此错误:

 ValueError at /findme/

 invalid literal for int() with base 10: 'id'

 Request Method:    GET
 Request URL:   http://127.0.0.1:8000/findme/
 Django Version:    1.4
 Exception Type:    ValueError
 Exception Value:   invalid literal for int() with base 10: 'id'

 Exception Location:    C:\Python27\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 537
 Python Executable:     C:\Python27\python.exe
  Python Version:   2.7.3

查看

from meebapp.models import Meekme

def cribdetail(request):
    post=Meekme.objects.get(id='id')
    return render_to_response('postdetail.html',{'post':post, 'Meekme':Meekme},context_instance=RequestContext(request))

我错过了什么?

解决方法

问题是这'id'是一个字符串,你需要在这里传递一个整数:

post=Meekme.objects.get(id='id')

它应该看起来像这样:

def cribdetail(request, meekme_id):
    post=Meekme.objects.get(id=meekme_id)
    return render_to_response('postdetail.html',{'post':post, 'Meekme':Meekme},context_instance=RequestContext(request))

其中meekme_id是一个整数,它是URL的一部分。您的URL配置应包含:

url(r'^example/(?P<meekme_id>\d+)/$', 'example.views.cribdetail'),

当您访问时example/3/,这意味着Django将调用cribdetail分配给值3 的视图meekme_id。有关更多详细信息,请参阅Django URL文档

问题

I'm trying to get data by id in my django app. The problem is that I don't know the kind of id the user will click on. I tried adding the below code in my views but I'm getting this error:

 ValueError at /findme/

 invalid literal for int() with base 10: 'id'

 Request Method:    GET
 Request URL:   http://127.0.0.1:8000/findme/
 Django Version:    1.4
 Exception Type:    ValueError
 Exception Value:   invalid literal for int() with base 10: 'id'

 Exception Location:    C:\Python27\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 537
 Python Executable:     C:\Python27\python.exe
  Python Version:   2.7.3

Views

from meebapp.models import Meekme

def cribdetail(request):
    post=Meekme.objects.get(id='id')
    return render_to_response('postdetail.html',{'post':post, 'Meekme':Meekme},context_instance=RequestContext(request))

What I'm I missing?

解决方法

The problem is that 'id' is a string and you need to pass an integer here:

post=Meekme.objects.get(id='id')

It should most likely look like this:

def cribdetail(request, meekme_id):
    post=Meekme.objects.get(id=meekme_id)
    return render_to_response('postdetail.html',{'post':post, 'Meekme':Meekme},context_instance=RequestContext(request))

where meekme_id is an integer that is part of the URL. Your URL configuration should contain:

url(r'^example/(?P<meekme_id>\d+)/$', 'example.views.cribdetail'),

When you visit example/3/, that means Django will call the view cribdetail with the value 3 assigned to meekme_id. See the Django URL documentation for more details.

相似信息