通过Django中的id获取对象 [英] Getting Objects by id in Django

查看:139
本文介绍了通过Django中的id获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过ID在我的django应用程序中获取数据。问题是我不知道用户点击的那种id。我尝试在我的意见中添加以下代码,但是我收到此错误:

  ValueError at / findme / 

int()的无效字面值为10:'id'

请求方法:GET
请求URL:http://127.0.0.1:8000/findme/
Django版本:1.4
异常类型:ValueError
异常值:基数为10的int()的无效字面值:'id'

异常位置:C:\Python27 \lib\site-package\django\db\models\fields\___init __。py in get_prep_value,line 537
Python可执行文件:C:\Python27\python.exe
Python版本: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(r'^ example /(?P< meekme_id> \d +)/ $' ,'example.views.cribdetail'),

当您访问示例/ 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.

这篇关于通过Django中的id获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆