官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 都匀市| 兴文县| 双城市| 出国| 正安县| 义马市| 琼海市| 揭西县| 徐州市| 剑阁县| 铜山县| 寻乌县| 永州市| 包头市| 深州市| 姚安县| 商南县| 藁城市| 教育| 疏勒县| 密山市| 文化| 绥江县| 镇坪县| 杂多县| 稷山县| 繁昌县| 镇坪县| 沛县| 房产| 乐昌市| 全州县| 广丰县| 额尔古纳市| 紫云| 泌阳县| 巴南区| 周宁县| 涞水县| 堆龙德庆县| 高州市|