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

Solution details

Python classes can treat a function as an attribute using the property decorator. Django models can use it as well. In the previous example, replace the function definition line with the following:

    @property 
    def age(self): 

Now, we can access the user's age with profile.age. Notice that the function's name is shortened as well.

An important shortcoming of a property is that it is invisible to the ORM, just like model methods are. You cannot use it in a QuerySet object. For example, this will not work, Profile.objects.exclude(age__lt=18). However, it is visible to views or templates.

In case you need to use it in a QuerySet object, you might want to use a Query expression. Use the annotate function to add a query expression to derive a calculated field from your existing fields.

A good reason to define a property is to hide the details of internal classes. This is formally known as the Law of Demeter (LoD). Simply put, the law states that you should only access your own direct members or use only one dot.

For example, rather than accessing profile.birthdate.year, it is better to define a profile.birthyear property. It helps you hide the underlying structure of the birthdate field this way.

Best Practice
Follow the LoD, and use only one dot when accessing a property.

An undesirable side effect of this law is that it leads to the creation of several wrapper properties in the model. This could bloat up models and make them hard to maintain. Use the law to improve your model's API and reduce coupling wherever it makes sense.

主站蜘蛛池模板: 通化市| 习水县| 吉安市| 神木县| 明星| 紫阳县| 南江县| 伊春市| 察隅县| 河曲县| 时尚| 天峨县| 虹口区| 陆川县| 全椒县| 绥江县| 浮山县| 黄梅县| 吴堡县| 黄大仙区| 瑞安市| 丰原市| 应用必备| 盐城市| 荔浦县| 堆龙德庆县| 肥乡县| 孟村| 久治县| 崇礼县| 财经| 黔南| 乌拉特后旗| 白城市| 洞头县| 山西省| 巢湖市| 施甸县| 大宁县| 福建省| 佛坪县|