How to add a calculated field to a Django model

后端 未结 5 1412
情书的邮戳
情书的邮戳 2020-11-28 23:59

I have a simple Employee model that includes firstname, lastname and middlename fields.

On the admin side and li

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 00:26

    That's not something you do as a field. Even if that syntax worked, it would only give the value when the class was defined, not at the time you access it. You should do this as a method, and you can use the @property decorator to make it look like a normal attribute.

    @property
    def name(self):
        return ''.join(
            [self.lastname,' ,', self.firstname, ' ', self.middlename])
    

    self.lastname etc appear as just their values, so no need to call any other method to convert them.

提交回复
热议问题