- Django Design Patterns and Best Practices
- Arun Ravindran
- 167字
- 2021-06-25 21:32:09
Problem details
Model fields store per-instance attributes, such as first name, last name, birthday, and so on. They are also stored in the database. However, we also need to access some derived attributes, such as full name or age.
They can be easily calculated from the database fields, hence need not be stored separately. In some cases, they can just be a conditional check such as eligibility for offers based on age, membership points, and active status.
A straightforward way to implement this is to define functions, such as get_age similar to the following:
class BaseProfile(models.Model): birthdate = models.DateField() #... def get_age(self): today = datetime.date.today() return (today.year - self.birthdate.year) - int( (today.month, today.day) < (self.birthdate.month, self.birthdate.day))
Calling profile.get_age() would return the user's age by calculating the difference in the years adjusted by one based on the month and date (that is, if this year's birthday is yet to come).
This could be invoked by a function call. However, it is much more readable (and Pythonic) to call it profile.age.
- Getting Started with Citrix XenApp? 7.6
- Android Jetpack開發(fā):原理解析與應(yīng)用實(shí)戰(zhàn)
- Getting Started with PowerShell
- R的極客理想:工具篇
- Visual Basic程序設(shè)計與應(yīng)用實(shí)踐教程
- Learning Network Forensics
- Python機(jī)器學(xué)習(xí)算法與實(shí)戰(zhàn)
- SQL Server數(shù)據(jù)庫管理與開發(fā)兵書
- 細(xì)說Python編程:從入門到科學(xué)計算
- 代替VBA!用Python輕松實(shí)現(xiàn)Excel編程
- Learning Grunt
- 大學(xué)計算機(jī)基礎(chǔ)實(shí)訓(xùn)教程
- R的極客理想:量化投資篇
- Mastering Data Analysis with R
- 軟件測試實(shí)驗(yàn)實(shí)訓(xùn)指南