django核心代码片段:
class ForeignKey(RelatedField, Field):
...
def db_type(self, connection):
rel_field = self.rel.get_related_field()
if (isinstance(rel_field, AutoField) or
(not connection.features.related_fields_match_type and
isinstance(rel_field, (PositiveIntegerField,
PositiveSmallIntegerField)))):
return IntegerField().db_type(connection=connection)
return rel_field.db_type(connection=connection)
这段代码非常糟糕,因为如果我定义一个继承自的自定义字段AutoField
,那么我的 db_type 方法将被忽略。
我想做的是隐藏我的类是AutoField
. 在 C++ 中,我会通过私有继承来做到这一点。
有没有办法欺骗isinstance
返回False
或隐藏继承?
我的自定义字段的代码:
class MyAutoField(models.AutoField):
def __init__(self, length, *args, **kwargs):
self.length = length
super(MyAutoField, self).__init__(*args, **kwargs)
def db_type(self, connection):
if connection.vendor == 'oracle':
return 'NUMBER(%s,0)' % (self.length)
if connection.vendor == 'postgresql':
if self.length <= 4:
return 'smallint'
if self.length <= 9:
return 'integer'
return 'bigint'
return super(MyAutoField, self).db_type(connection)