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

Problem details

Fat models, thin views is an adage commonly told to Django beginners. Ideally, your views should not contain anything other than presentation logic.

However, over time, pieces of code that cannot be placed anywhere else tend to go into models. Soon, models become a dump yard for the code.

Consider refactoring out a Service object if your model contains code for any of the following:

  1. Interactions with external services, for example, checking whether the user is eligible to get a SuperHeroProfile with a web service
  2. Helper tasks that do not deal with the database, for example, generating a short URL or random captcha for a user
  3. Making a short-lived object without a database state, for example, creating a JSON response for an AJAX call
  4. Functionality spanning multiple model instances yet do not belong to anyone
  5. Long-running tasks such as Celery tasks

Models in Django follow the Active Record pattern, that is, each class instance corresponds to a row in the database table. Ideally, they encapsulate both database access and application (or domain) logic. However, keep the application logic minimal.

While testing, if we find ourselves mocking the database even while not using it, then we need to consider breaking up the model class. A Service object is recommended in such situations.

主站蜘蛛池模板: 河北省| 牡丹江市| 内丘县| 黄大仙区| 仁寿县| 方山县| 新郑市| 莆田市| 石台县| 沈丘县| 菏泽市| 荆门市| 宝清县| 镶黄旗| 三亚市| 沾化县| 东兴市| 那坡县| 砀山县| 突泉县| 含山县| 论坛| 松桃| 会泽县| 阳朔县| 招远市| 巴林左旗| 广南县| 辽源市| 惠来县| 新干县| 若羌县| 大理市| 乌拉特前旗| 台东市| 华阴市| 丹阳市| 洛南县| 临海市| 德保县| 武功县|