[英]Is there an easy way to create derived attributes in Django Model/Python classes?
Every Django model has a default primary-key id
created automatically. 每个Django模型都有一个自动创建的默认主键
id
。 I want the model objects to have another attribute big_id
which is calculated as: 我希望模型对象具有另一个属性
big_id
,其计算方法如下:
big_id = id * SOME_CONSTANT
I want to access big_id
as model_obj.big_id
without the corresponding database table having a column called big_id
. 我想访问
big_id
作为model_obj.big_id
而没有相应的数据库表有一个名为big_id
的列。
Is this possible? 这可能吗?
Well, django model instances are just python objects, or so I've been told anyway :P 好吧,django模型实例只是python对象,所以我还是被告知了:P
That is how I would do it: 我就是这样做的:
class MyModel(models.Model):
CONSTANT = 1234
id = models.AutoField(primary_key=True) # not really needed, but hey
@property
def big_id(self):
return self.pk * MyModel.CONSTANT
Obviously, you will get an exception if you try to do it with an unsaved model. 显然,如果您尝试使用未保存的模型,则会出现异常。 You can also precalculate the big_id value instead of calculating it every time it is accessed.
您还可以预先计算big_id值,而不是每次访问时计算它。
class Person(models.Model):
x = 5
name = ..
email = ..
def _get_y(self):
if self.id:
return x * self.id
return None
y = property(_get_y)
You've got two options I can think of right now: 你现在有两个我能想到的选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.