在miikkas的建议下,我使用model.Manager提出了以下解决方案,可以在查询uuid时检索id字段。数据库创建时,ID是一个用于十六进制字符串的varchar字段,并且我正在添加一个顺序整数ID字段,以便可以使用Django的auth模块(这需要ID)。我希望逐步完成此操作,因此这个方法很“hacky”。
if DEVELOPMENT['merging_to_sequential_ids_incomplete']:
class ModelManager(models.Manager):
def get(self, *args, **kwargs):
if 'uuid' in kwargs:
kwargs['id'] = kwargs.pop('uuid')
return super(ModelManager, self).get(*args, **kwargs)
class Model(models.Model):
if DEVELOPMENT['merging_to_sequential_ids_incomplete']:
print >>sys.stderr, 'WARNING: uuid now a synonym to id'
id = models.CharField(max_length = 32,
primary_key = True, default = uuid_string)
objects = ModelManager()
uuid = property(lambda self: self.id)
else:
id = models.AutoField(primary_key = True)
uuid = models.CharField(max_length = 32, ...
现在我可以:
cd myapp && ../djangopython manage.py shell
WARNING: uuid now a synonym to id
setting up special admin settings
Python 2.7.8 (default, Nov 18 2014, 16:29:10)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from myapp.models import *
>>> Client.objects.get(uuid=u'18b86bd7b58e4c0186f7654045ce81d9')
<Client: jc@example.net>
>>> _.uuid
u'18b86bd7b58e4c0186f7654045ce81d9'
filter
可以用相同的方式进行。
也许这可以帮助指导其他人寻找一种使用Django模型字段的“别名”或“同义词”的方法。但我不认为这会对OP有所帮助。自定义字段类型可能是更好的通用方法。