简体   繁体   English

有没有一种在Django Model / Python类中创建派生属性的简单方法?

[英]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: 你现在有两个我能想到的选择:

  1. Since you don't want the field in the database your best bet is to define a method on the model that returns self.id * SOME_CONSTANT, say you call it big_id(). 由于您不希望数据库中的字段,最好的办法是在模型上定义一个返回self.id * SOME_CONSTANT的方法,比如你称之为big_id()。 You can access this method anytime as yourObj.big_id(), and it will be available in templates as yourObj.big_id (you might want to read about the "magic dot" in django templates). 您可以随时以yourObj.big_id()访问此方法,并且它将作为yourObj.big_id在模板中提供(您可能希望阅读django模板中的“魔术点”)。
  2. If you don't mind it being in the DB, you can override the save method on your object to calculate id * SOME_CONSTANT and store it in a big_id field. 如果您不介意它在DB中,您可以覆盖对象的save方法来计算id * SOME_CONSTANT并将其存储在big_id字段中。 This would save you from having to calculate it every time, since I assume ID isn't going to change 这样可以避免每次都计算它,因为我假设ID不会改变

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM