我正在使用旧数据库,并且在将一个表中的外键连接到另一个表中的主键时遇到一些问题。我非常感谢任何帮助。下面是模型和我的shell +错误。提前谢谢。
型号:
class SectionMaster(models.Model):
. . .
crs_cde = models.ForeignKey('SectionSchedules', max_length=30, db_column=u'CRS_CDE', related_name='sm_crs_cde')
. . .
class SectionSchedules(models.Model):
. . .
crs_cde = models.CharField(max_length=30, db_column=u'CRS_CDE')
. . .
错误:
>>> q = SectionMaster.objects.filter(trm_cde=20).filter(yr_cde=2012)
>>> q2 = SectionSchedules.objects.filter(trm_cde=20).filter(yr_cde=2012)
>>> for course in q:
... for course2 in q2:
... if course.crs_cde == course2.crs_cde: ## also tried course.crs_cde_id
... print course.crs_cde, course.crs_title, course2.begin_dte
...
Traceback (most recent call last):
File "<console>", line 3, in <module>
File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line
350, in __get__
rel_obj = qs.get(**params)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 358, in g
et
clone = self.filter(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 624, in f
ilter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 642, in _
filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1250,
in add_q
can_reuse=used_aliases, force_having=force_having)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1185,
in add_filter
connector)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py", line 69, i
n add
value = obj.prepare(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\sql\where.py", line 320,
in prepare
return self.field.get_prep_lookup(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
972, in get_prep_lookup
return super(IntegerField, self).get_prep_lookup(lookup_type, value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
310, in get_prep_lookup
return self.get_prep_value(value)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: '0BJ 226 1
'
答案 0 :(得分:3)
我希望你希望ForeignKey上的to_field='crs_cde'
告诉它查看目标表的crs_cde
字段的值,而不是(整数)主键。
答案 1 :(得分:0)
检查您的列crs_cde_id
- 它应该是数据库中的Int类型。但似乎你在那里有角色。