django ORM模型如下
class DeviceType(models.Model):
name = models.CharField(_(u'设备类型名称'), max_length=64)
class Device(models.Model)
d_type = models.ForeignKey(DeviceType, db_column=u'device_type_id')
# mo'ren的命名方式
# device_type = models.ForeignKey(DeviceType, db_column=u'device_type_id')
平常外键的命名方式就是为Djano默认的字段名后加id。使用db_column指定之后,不能通过Device实例o.device_type_id访问,而是o.d_type_id。django ORM外键字段的命名和db_column无关么?
无关。
这个字段有两个名字,一个是 d_type_id,它是 python 层面的;另一个是 device_type_id,它是最终存在数据库中的列名。而你通过实例 Device 访问,是在 python 层面的,如果访问 device_type_id 是会报错的:
你在 python shell 中查看
dir(Device)
或者dir(d)
都是找不到device_type_id
的,只有'd_type', 'd_type_id',
: