2011-10-31 117 views
0

帮助!为什么我的两个相同类型的django对象的行为不同?

我有两个对象,我在django中使用不同的技术创建;

>>> from django.contrib.contenttypes.models import ContentType 
>>> from myproject.models import Building 

方法A

>>> content_type = ContentType.objects.get(app_label='myproject', model='Building') 

>>> content_class = content_type.model_class() 

>>> content_query = content_class.objects.raw("Select * from pms_building where name like '%build%' ") 

>>> type(content_query) 

<class 'django.db.models.query.RawQuerySet'> 
>>> content_query[0] 
# error .... 
# Attribute: 'str' object has no attribute 'items' 

方法B

>>> bld = Building.objects.raw("Select * from pms_building where name like '%build%' ") 

>>> type(bld) 

<class 'django.db.models.query.RawQuerySet'> 

>>>bld[0] 
<Building: Building A> 

我的问题是,为什么同类型的两个对象行为不同?

迦特

+0

我的猜测会是两个不同的__init__方法。使用dir(bld)和dir(content_query)来查看他们定义的内容。 –

+0

他们是一样的。 – gath

回答

2

,当你调用content_query[0]只执行的SQL查询,所以查询将在这一点上,如果事情是错content_class例如失败。至少我注意到,你从第一行忘了objects

content_type = ContentType.objects.get(app_label='myproject', model='Building') 

编辑:我得到了“‘海峡’对象有没有属性‘项目’”的错误时,%-marks被错误地解释。这固定它对我来说:

s = "%build%" 
content_query = content_class.objects.raw("Select * from pms_building where namelike %s", [s]) 
+0

*编辑*无关,固定,虽然我评论= P – Izkata

+0

对不起,错字,已经省略了“对象”编辑问题,问题仍然存在 – gath

+0

@gath两种方法都适合我。你使用的是什么Django版本和数据库? – Lycha

相关问题