Django 模型方法或计算作为数据库中的字段 [英] Django Model Method or Calculation as Field in Database

查看:34
本文介绍了Django 模型方法或计算作为数据库中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Django ~=1.11 和 Python 3.6

我需要将计算"变量作为字段存储在 Django 模型数据库中.

I need to store 'calculated' variables as fields in the Django model database.

这是一个模型:

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.具体来说,我将每个字段的部分合并为一个字符串变量(详情如下).我能够让它作为属性工作,但我不知道如何在数据库中存储计算字段.

I am creating a Unique ID using these fields. Specifically, I'm conjoining parts of each field into one string variable (details below). I was able to get this to work as a Property but I don't know how to store a calculated field in the database.

"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 做类似的事情.这是我的计算结果:

I want to do a similar thing with Age. Here's what I have as a calculation:

"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 模型中的字段.执行这些操作时的最佳实践是什么?我是否需要先初始化字段,然后对这些字段进行某种更新查询?

So I'd like to store the UniqueID and Age variables in the database, as fields in the Person model. What is the best practice when doing these? Do I need to initialize the fields first, then do some sort of update query to these?

注意:据我所知,当前使用属性"的代码可用于在视图中呈现,但并未存储在数据库中.

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

Thanks in advance! Please help me improve what I already have.

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

UPDATE: Here is code that worked for me. The problem was that I needed to drop the parentheses in the save() section, after self.unique_id=self.get_unique_id . It has been suggested to drop age from the database, and leave it as a property.

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

推荐答案

你必须覆盖你模型 Personsave 方法并创建 unique_idage 字段.

You have to override the save method of yout Model Person and create unique_id and age field in the Model.

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 是用类属性不需要的()"调用的.

UPDATE: Previously the self.get_unique_id and self.get_age were being called with '()' which is not required for class properties.

这篇关于Django 模型方法或计算作为数据库中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆