- Django Design Patterns and Best Practices
- Arun Ravindran
- 267字
- 2021-06-25 21:32:09
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.
- iOS Game Programming Cookbook
- 微服務與事件驅動架構
- Learning Chef
- Python Data Analysis(Second Edition)
- Getting Started with LLVM Core Libraries
- C語言程序設計
- PLC應用技術(三菱FX2N系列)
- Python深度學習原理、算法與案例
- Android驅動開發(fā)權威指南
- Canvas Cookbook
- Django實戰(zhàn):Python Web典型模塊與項目開發(fā)
- Learning Image Processing with OpenCV
- Flask開發(fā)Web搜索引擎入門與實戰(zhàn)
- 讀故事學編程:Python王國歷險記
- 開發(fā)者測試