Django 模型方法或计算作为数据库中的字段

Django Model Method or Calculation as Field in Database

使用 Django ~=1.11 和 Python 3.6

我需要将 'calculated' 个变量作为字段存储在 Django 模型数据库中。

这是一个模型:

from django.db import models
from datetime import date

class Person(model.Model)
    "Last Name"
    last_name = models.CharField(max_length=25)

    "Birthday"
    birth_date = models.DateField()

    "City of birth"
    city_of_birth = models.CharField(max_length=25)

我正在使用这些字段创建一个唯一 ID。具体来说,我将每个字段的部分连接到一个字符串变量中(详情如下)。我能够使它作为 属性 工作,但我不知道如何在数据库中存储计算字段。

"Unique ID"
def get_id(self):
    a = self.last_name[:2].upper()     #First 2 letters of last name
    b = self.birth_date.strftime('%d')     #Day of the month as string
    c = self.city_of_birth[:2].upper()     #First 2 letters of city
    return a + b + c 
unique_id = property(get_id)

我想对 Age 做类似的事情。这是我的计算结果:

"Age calculated from Birth Date"
def get_age(self):
    return int((datetime.date.now() - self.birth_date.days) / 365.25)
age = property(get_age)

所以我想将 UniqueID 和 Age 变量存储在数据库中,作为 Person 模型中的字段。执行这些操作时的最佳做法是什么?我是否需要先初始化字段,然后对这些字段进行某种更新查询?

注意:据我了解,当前使用'property'的代码可在视图中进行渲染,但不会存储在数据库中。

提前致谢!请帮助我改进我已有的东西。

更新: 这是对我有用的代码。问题是我需要在 self.unique_id=self.get_unique_id 之后的 save() 部分中删除括号。建议从数据库中删除年龄,并将其保留为 属性.

class Person(models.Model):
    unique_id = models.CharField(max_length=6, blank=True)
    last_name = models.CharField(max_length=25)
    birth_date = models.DateField()
    city_of_birth = models.CharField(max_length=25)

    @property
    def get_unique_id(self):
        a = self.last_name[:2].upper()     #First 2 letters of last name
        b = self.birth_date.strftime('%d')     #Day of the month as string
        c = self.city_of_birth[:2].upper()     #First 2 letters of city
        return a + b + c 

    @property
    def age(self):
        return relativedelta(self.birth_date.days, datetime.date.now()).years

    def save(self, *args, **kwarg):
        self.unique_id = self.get_unique_id
        super(Person, self).save(*args, **kwarg)

    def __str__(self):
        return self.unique_id

模型对这种事情有clean方法:

This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field

松开 属性 并添加一个名为 'unique_id' 的字段,它应该是一个 CharField。将 get_id 重命名为 clean 并将 return 语句替换为:

self.unique_id = a + b + c

如果您确定这总是会生成唯一的字符串,请考虑将此字段设为主键。然而,如果这个模型已经被迁移,你不能将它命名为 id,因为 Django 已经为你创建了一个字段 id 作为一个 AutoField,所以它需要两次迁移,如果你'重新设置名称 'id'(稍后可以压缩)。

您必须覆盖模型 Personsave 方法并在模型中创建 unique_idage 字段。

from dateutil.relativedelta import relativedelta
from datetime import datetime

class Person(model.Model)
     unique_id = models.CharField(max_length=25)
     age = models.IntegerField()
     last_name = models.CharField(max_length=25)
     birth_date = models.DateField()
     city_of_birth = models.CharField(max_length=25)
 
     @property
     def get_unique_id(self):
         a = self.last_name[:2].upper()     #First 2 letters of last name
         b = self.birth_date.strftime('%d')     #Day of the month as string
         c = self.city_of_birth[:2].upper()     #First 2 letters of city
         return a + b + c 
 
     @property
     def get_age(self):
         return relativedelta(self.birth_date.days, datetime.date.now()).years
     

     def save(self, *args, **kwargs):
          self.unique_id = self.get_unique_id
          self.age = self.get_age
          super(Person, self).save(*args, **kwargs)

更新:以前 self.get_unique_idself.get_age 是使用“()”调用的,这对于 class 属性不是必需的。