修改django的默认"_id"相关对象的后缀 [英] Modifying django's default "_id" suffix for related objects
问题描述
我正在将django与旧版系统和数据库集成,并具有一个类似于以下的模型
I am integrating django with a legacy system and database and have a model that looks like this
class Label(models.Model)
iLabelID = models.IntegerField(db_column='LABELID', primary_key=True)
organization = models.OneToOneField(Organization, related_name='labels', db_column='ORGANIZATION')
sLabelText = models.CharField(max_length=42)
使用此表示法(或多或少匈牙利表示法)是该项目的要求.
Using this notation (more or less hungarian notation) is a requirement of the project.
以下内容将在Django中工作:
The following will work in django:
>>> Label.objects.get(organization_id=1)
但是我希望能够这样写:
But I want to be able to write this:
>>> Label.objects.get(iOrganizationID=1)
我尝试使用
class MyOneToOneField(models.OneToOneField):
def get_attname(self):
# default is:
# return '%s_id' % self.name
return 'i%s%sID' % (self.name[0].upper(), self.name[1:])
但这是我在尝试使用它时遇到的错误:
But this is the error I get when trying to use it:
>>> Label.objects.get(iOrganizationID=1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "django/db/models/query.py", line 301, in get
num = len(clone)
File "django/db/models/query.py", line 77, in __len__
self._fetch_all()
File "django/db/models/query.py", line 854, in _fetch_all
self._result_cache = list(self.iterator())
File "django/db/models/query.py", line 230, in iterator
obj = model(*row_data)
File "django/db/models/base.py", line 347, in __init__
setattr(self, field.attname, val)
AttributeError: can't set attribute
这是另一个痛苦点:
我希望生成一些JSON.此JSON将被馈送到我无法控制的系统的另一部分(无法更改名称).我希望我可以执行以下操作:
I wish to generate some JSON. This JSON will be fed to another part of the system on which I have no control (not possible to change names). I wish I could do the following:
json.dumps(list(Label.objects.values('iLabelID', 'iOrganizationID', 'sAnotherValue')))
但这是不可能的.我必须这样做
But this is not possible. I have to do this
list(Label.objects.values('iLabelID', 'organization_id', 'sAnotherValue'))
然后手动将 organization_id
映射到 iOrganizationID
,尽管这对于标签ID来说不是问题.这样会使代码更难维护,更易阅读,并且执行速度较慢.
And then manually map organization_id
to iOrganizationID
, although this is not a problem for the label's ID. It makes code more difficult to maintain, to read, and slower to execute.
请注意,这不是不是特定于匈牙利符号,您可能需要后缀 _identifier
或 _pk
或其他代替的后缀_id
.
Note that this is not specific to hungarian notation, you may need to suffix with _identifier
or _pk
or whatever instead of _id
.
我一定犯了另一个错误,因为正如lanzz指出的,get_attname确实起作用-_-
I must have made another error because as lanzz pointed out get_attname does work -_-
推荐答案
我通过对您的代码进行了一些修改来解决了该问题:
I solved it using some modifications of your code:
class CustomAttrNameForeignKey(djangoFields.related.ForeignKey):
def __init__(self, *args, **kwargs):
attname = kwargs.pop('attrname', None)
super(CustomAttrNameForeignKey, self).__init__(*args, **kwargs)
self.attname = attname or super(CustomAttrNameForeignKey, self).get_attname()
def get_attname(self):
return self.attname
class AModelUsingThis(djangoModels.Model):
snapshot = CustomAttrNameForeignKey(
ParentalModel, db_column="timestamp", to_field="timestamp",
attrname='timestamp', related_name="children")
在这种情况下,我们在模型中获得FK的属性,该属性完全没有后缀,但具有给定的名称.我尚未在数据库上对其进行过测试,但只是尝试使用给定的自定义FK实例化模型-效果很好.
In this case we get in the model an attribute for FK with no suffix at all, but with the name given. I haven't tested it yet on DB, but just tried to instantiate model also with this custom FK given -- it works fine.
这篇关于修改django的默认"_id"相关对象的后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!