我正在反省模型中某些字段的类型,特别是我对检索依赖于 RDBMS 的类型感兴趣,即"VARCHAR(20)"
,而不是 Django 字段类(django.db.models.CharField
在本例中)。
但是,我遇到了关系问题,因为数据库将两个表与varchar
主键混合在一起,而另一个表与integer
pks 混合在一起(所以我不能做出任何假设)。
到目前为止,我已尝试使用以下代码检索字段类型:
# model is a django.db.model class
for field in model._meta.get_fields(include_parents=False):
try:
# this code works for anything but relations
ft = field.db_type(connection=connection)
except:
# I'm introspecting a relation -> I would like to retrieve the field type of the related object's pk
ft = field.related_model.pk.db_type(connection=connection)
在处理关系时,失败并出现以下错误:
'property' object has no attribute 'db_type'
当它失败时,它field.__class__
似乎是一个ManyToOneRel
对象,如果这可能有帮助的话。值得注意的是,代码必须与新的 Django 1.8 兼容_meta
。