SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
sunscrapers.comYour favored tech partner.
Thick QuerySets and Thin Models, or
Where to Put Business Logic in
Django
Michał Nakoneczny
2017-05-19
sunscrapers.comYour favored tech partner.
A layer which encodes the real-world business rules that
determine how data can be created, displayed, stored, and
changed.
Business Logic Layer
sunscrapers.comYour favored tech partner.
Idea 1: Fat Models
sunscrapers.comYour favored tech partner.
A Company Blog
class Post(Model):
STATUS_DRAFT, STATUS_APPROVED, STATUS_PUBLISHED = range(3)
STATUS_CHOICES = (
(STATUS_DRAFT, _('Draft')),
(STATUS_APPROVED, _('Approved')),
(STATUS_PUBLISHED, _('Published'))
)
title = models.CharField(max_length=255)
text = models.TextField()
status = models.PositiveSmallIntegerField(
choices=STATUS_CHOICES,
default=STATUS_DRAFT
)
sunscrapers.comYour favored tech partner.
BL: Approving and Publishing
class Post(Model):
...
def approve(self):
self.status = Post.STATUS_APPROVED
self.save()
def publish(self):
if self.status != Post.STATUS_APPROVED:
raise PostInvalidStatusError()
self.status = Post.STATUS_APPROVED
self.save()
sunscrapers.comYour favored tech partner.
Pros:
● Testable;
● Readable;
● DRY?
Cons:
● Unmaintanable in a large code base;
● Leads to unoptimised solutions.
Idea 1: Fat Models
sunscrapers.comYour favored tech partner.
Idea 2: Forms/Views/Serializers
sunscrapers.comYour favored tech partner.
sunscrapers.comYour favored tech partner.
Idea 3: Services
sunscrapers.comYour favored tech partner.
BL: Approving and Publishing
def approve_post(post):
post.status = Post.STATUS_APPROVED
post.save()
def publish_post(post):
if post.status != Post.STATUS_APPROVED:
raise PostInvalidStatusError()
post.status = Post.STATUS_APPROVED
post.save()
sunscrapers.comYour favored tech partner.
Pros:
● Testable;
● Readable?;
● DRY
Cons:
● Unstructured in a large code base;
● Can lead to unoptimised solutions.
Idea 3: Services
sunscrapers.comYour favored tech partner.
Idea 4: QuerySets/Managers
sunscrapers.comYour favored tech partner.
BL: Approving and Publishing
class PostQuerySet(QuerySet):
def approve(self):
return self.update(status=Post.STATUS_APPROVED)
def publish(self):
return self.filter(status=Post.STATUS_APPROVED).update(
status=Post.STATUS_PUBLISHED)
class Post(Model):
...
objects = PostQuerySet.as_manager()
sunscrapers.comYour favored tech partner.
Pros:
● Testable;
● Readable;
● DRY;
● Optimised (unless you do something stupid).
Cons:
● Checking Business Logic rules is more complicated.
● Integrations get more difficult.
Idea 4: QuerySets/Managers
sunscrapers.comYour favored tech partner.
Business Logic Rules
def publish(self):
return self.filter(status=Post.STATUS_APPROVED).update(
status=Post.STATUS_PUBLISHED)
def publish(self):
if self.exclude(status=Post.STATUS_APPROVED).exists():
raise PostInvalidStatusError()
return self.update(status=Post.STATUS_PUBLISHED)
sunscrapers.comYour favored tech partner.
Integrations
def pay(self):
Posts_data = …
pay_service = PayService()
try:
pay_service.pay_batch(posts_data)
return self.update (status=Post.STATUS_PAID)
except …:
...
sunscrapers.comYour favored tech partner.
Thanks!
Questions?

Más contenido relacionado

Similar a Fat query sets and Skinny Models

Agile Data Science 2.0 - Big Data Science Meetup
Agile Data Science 2.0 - Big Data Science MeetupAgile Data Science 2.0 - Big Data Science Meetup
Agile Data Science 2.0 - Big Data Science MeetupRussell Jurney
 
Django and working with large database tables
Django and working with large database tablesDjango and working with large database tables
Django and working with large database tablesIlian Iliev
 
Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...
Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...
Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...BIWUG
 
Quick start guide to java script frameworks for sharepoint apps spsbe-2015
Quick start guide to java script frameworks for sharepoint apps spsbe-2015Quick start guide to java script frameworks for sharepoint apps spsbe-2015
Quick start guide to java script frameworks for sharepoint apps spsbe-2015Sonja Madsen
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-labAmit Sharma
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkOdoo
 
Crack4sure microsoft az-500 dumps
Crack4sure microsoft az-500 dumpsCrack4sure microsoft az-500 dumps
Crack4sure microsoft az-500 dumpsshron frank
 
MS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmxMS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmxsqlserver content
 
MS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmxMS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmxDataminingTools Inc
 
如何建立企業級應用的商業規則引擎
如何建立企業級應用的商業規則引擎如何建立企業級應用的商業規則引擎
如何建立企業級應用的商業規則引擎CodeData
 
Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...
Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...
Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...Amit Sharma
 
Google Tag Manager (GTM)
Google Tag Manager (GTM)Google Tag Manager (GTM)
Google Tag Manager (GTM)Dragos Ionita
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-labAmit Sharma
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptxMuqaddarNiazi1
 
mongoDB Performance
mongoDB PerformancemongoDB Performance
mongoDB PerformanceMoshe Kaplan
 
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...Amazon Web Services Korea
 

Similar a Fat query sets and Skinny Models (20)

Agile Data Science 2.0 - Big Data Science Meetup
Agile Data Science 2.0 - Big Data Science MeetupAgile Data Science 2.0 - Big Data Science Meetup
Agile Data Science 2.0 - Big Data Science Meetup
 
Django and working with large database tables
Django and working with large database tablesDjango and working with large database tables
Django and working with large database tables
 
Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...
Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...
Quickstartguidetojavascriptframeworksforsharepointapps spsbe-2015-15041903264...
 
Quick start guide to java script frameworks for sharepoint apps spsbe-2015
Quick start guide to java script frameworks for sharepoint apps spsbe-2015Quick start guide to java script frameworks for sharepoint apps spsbe-2015
Quick start guide to java script frameworks for sharepoint apps spsbe-2015
 
Drools rule Concepts
Drools rule ConceptsDrools rule Concepts
Drools rule Concepts
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-lab
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo Framework
 
Crack4sure microsoft az-500 dumps
Crack4sure microsoft az-500 dumpsCrack4sure microsoft az-500 dumps
Crack4sure microsoft az-500 dumps
 
MS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmxMS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmx
 
MS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmxMS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmx
 
如何建立企業級應用的商業規則引擎
如何建立企業級應用的商業規則引擎如何建立企業級應用的商業規則引擎
如何建立企業級應用的商業規則引擎
 
Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...
Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...
Salesforce interview-preparation-toolkit-formula-and-validation-rules-in-sale...
 
Google Tag Manager (GTM)
Google Tag Manager (GTM)Google Tag Manager (GTM)
Google Tag Manager (GTM)
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-lab
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
Df12 Performance Tuning
Df12 Performance TuningDf12 Performance Tuning
Df12 Performance Tuning
 
mongoDB Performance
mongoDB PerformancemongoDB Performance
mongoDB Performance
 
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
[AWS Innovate 온라인 컨퍼런스] 간단한 Python 코드만으로 높은 성능의 기계 학습 모델 만들기 - 김무현, AWS Sr.데이...
 

Más de Sunscrapers

DVCS Workflows for Teams - Bartek Rychlicki
DVCS Workflows for Teams - Bartek RychlickiDVCS Workflows for Teams - Bartek Rychlicki
DVCS Workflows for Teams - Bartek RychlickiSunscrapers
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof SkarupaSunscrapers
 
How to justify your recommendation - Łukasz Karwacki
How to justify your recommendation - Łukasz KarwackiHow to justify your recommendation - Łukasz Karwacki
How to justify your recommendation - Łukasz KarwackiSunscrapers
 
PostgreSQL and JSON with Python - Przemek Lewandowski
PostgreSQL and JSON  with Python - Przemek Lewandowski PostgreSQL and JSON  with Python - Przemek Lewandowski
PostgreSQL and JSON with Python - Przemek Lewandowski Sunscrapers
 
Py2 - Py3 migration - Krzysztof Skarupa
Py2  - Py3 migration - Krzysztof SkarupaPy2  - Py3 migration - Krzysztof Skarupa
Py2 - Py3 migration - Krzysztof SkarupaSunscrapers
 
Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)
Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)
Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)Sunscrapers
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingSunscrapers
 
Foundations of Foundation 6 - Jakub Włodaczyk (pl)
Foundations of Foundation 6 - Jakub Włodaczyk (pl)Foundations of Foundation 6 - Jakub Włodaczyk (pl)
Foundations of Foundation 6 - Jakub Włodaczyk (pl)Sunscrapers
 
Jaka przyszłość czeka polskich programistów?
Jaka przyszłość czeka polskich programistów?Jaka przyszłość czeka polskich programistów?
Jaka przyszłość czeka polskich programistów?Sunscrapers
 
Creating value for customers - understanding context
Creating value for customers - understanding contextCreating value for customers - understanding context
Creating value for customers - understanding contextSunscrapers
 

Más de Sunscrapers (11)

DVCS Workflows for Teams - Bartek Rychlicki
DVCS Workflows for Teams - Bartek RychlickiDVCS Workflows for Teams - Bartek Rychlicki
DVCS Workflows for Teams - Bartek Rychlicki
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
 
How to justify your recommendation - Łukasz Karwacki
How to justify your recommendation - Łukasz KarwackiHow to justify your recommendation - Łukasz Karwacki
How to justify your recommendation - Łukasz Karwacki
 
PostgreSQL and JSON with Python - Przemek Lewandowski
PostgreSQL and JSON  with Python - Przemek Lewandowski PostgreSQL and JSON  with Python - Przemek Lewandowski
PostgreSQL and JSON with Python - Przemek Lewandowski
 
Py2 - Py3 migration - Krzysztof Skarupa
Py2  - Py3 migration - Krzysztof SkarupaPy2  - Py3 migration - Krzysztof Skarupa
Py2 - Py3 migration - Krzysztof Skarupa
 
Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)
Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)
Introduction to ReactJS - Comparison to AngularJS 2 - Robert Piękoś (pl)
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Foundations of Foundation 6 - Jakub Włodaczyk (pl)
Foundations of Foundation 6 - Jakub Włodaczyk (pl)Foundations of Foundation 6 - Jakub Włodaczyk (pl)
Foundations of Foundation 6 - Jakub Włodaczyk (pl)
 
Jaka przyszłość czeka polskich programistów?
Jaka przyszłość czeka polskich programistów?Jaka przyszłość czeka polskich programistów?
Jaka przyszłość czeka polskich programistów?
 
Interruptions
InterruptionsInterruptions
Interruptions
 
Creating value for customers - understanding context
Creating value for customers - understanding contextCreating value for customers - understanding context
Creating value for customers - understanding context
 

Último

SaaStr Workshop Wednesday w/ Kyle Norton, Owner.com
SaaStr Workshop Wednesday w/ Kyle Norton, Owner.comSaaStr Workshop Wednesday w/ Kyle Norton, Owner.com
SaaStr Workshop Wednesday w/ Kyle Norton, Owner.comsaastr
 
Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸mathanramanathan2005
 
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...漢銘 謝
 
Genshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxGenshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxJohnree4
 
The 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software EngineeringThe 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software EngineeringSebastiano Panichella
 
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC  - NANOTECHNOLOGYPHYSICS PROJECT BY MSC  - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC - NANOTECHNOLOGYpruthirajnayak525
 
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSimulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSebastiano Panichella
 
The Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationThe Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationNathan Young
 
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...marjmae69
 
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRRINDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRRsarwankumar4524
 
SBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSebastiano Panichella
 
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRachelAnnTenibroAmaz
 
Early Modern Spain. All about this period
Early Modern Spain. All about this periodEarly Modern Spain. All about this period
Early Modern Spain. All about this periodSaraIsabelJimenez
 
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.KathleenAnnCordero2
 
miladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxmiladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxCarrieButtitta
 
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...Henrik Hanke
 
Quality by design.. ppt for RA (1ST SEM
Quality by design.. ppt for  RA (1ST SEMQuality by design.. ppt for  RA (1ST SEM
Quality by design.. ppt for RA (1ST SEMCharmi13
 
Event 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxEvent 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxaryanv1753
 
Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Escort Service
 
Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...
Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...
Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...Krijn Poppe
 

Último (20)

SaaStr Workshop Wednesday w/ Kyle Norton, Owner.com
SaaStr Workshop Wednesday w/ Kyle Norton, Owner.comSaaStr Workshop Wednesday w/ Kyle Norton, Owner.com
SaaStr Workshop Wednesday w/ Kyle Norton, Owner.com
 
Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸Mathan flower ppt.pptx slide orchids ✨🌸
Mathan flower ppt.pptx slide orchids ✨🌸
 
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
 
Genshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptxGenshin Impact PPT Template by EaTemp.pptx
Genshin Impact PPT Template by EaTemp.pptx
 
The 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software EngineeringThe 3rd Intl. Workshop on NL-based Software Engineering
The 3rd Intl. Workshop on NL-based Software Engineering
 
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC  - NANOTECHNOLOGYPHYSICS PROJECT BY MSC  - NANOTECHNOLOGY
PHYSICS PROJECT BY MSC - NANOTECHNOLOGY
 
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with AerialistSimulation-based Testing of Unmanned Aerial Vehicles with Aerialist
Simulation-based Testing of Unmanned Aerial Vehicles with Aerialist
 
The Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism PresentationThe Ten Facts About People With Autism Presentation
The Ten Facts About People With Autism Presentation
 
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
Gaps, Issues and Challenges in the Implementation of Mother Tongue Based-Mult...
 
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRRINDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
 
SBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation TrackSBFT Tool Competition 2024 -- Python Test Case Generation Track
SBFT Tool Competition 2024 -- Python Test Case Generation Track
 
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
 
Early Modern Spain. All about this period
Early Modern Spain. All about this periodEarly Modern Spain. All about this period
Early Modern Spain. All about this period
 
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
PAG-UNLAD NG EKONOMIYA na dapat isaalang alang sa pag-aaral.
 
miladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptxmiladyskindiseases-200705210221 2.!!pptx
miladyskindiseases-200705210221 2.!!pptx
 
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
DGT @ CTAC 2024 Valencia: Most crucial invest to digitalisation_Sven Zoelle_v...
 
Quality by design.. ppt for RA (1ST SEM
Quality by design.. ppt for  RA (1ST SEMQuality by design.. ppt for  RA (1ST SEM
Quality by design.. ppt for RA (1ST SEM
 
Event 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptxEvent 4 Introduction to Open Source.pptx
Event 4 Introduction to Open Source.pptx
 
Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170Call Girls In Aerocity 🤳 Call Us +919599264170
Call Girls In Aerocity 🤳 Call Us +919599264170
 
Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...
Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...
Presentation for the Strategic Dialogue on the Future of Agriculture, Brussel...
 

Fat query sets and Skinny Models

  • 1. sunscrapers.comYour favored tech partner. Thick QuerySets and Thin Models, or Where to Put Business Logic in Django Michał Nakoneczny 2017-05-19
  • 2. sunscrapers.comYour favored tech partner. A layer which encodes the real-world business rules that determine how data can be created, displayed, stored, and changed. Business Logic Layer
  • 3. sunscrapers.comYour favored tech partner. Idea 1: Fat Models
  • 4. sunscrapers.comYour favored tech partner. A Company Blog class Post(Model): STATUS_DRAFT, STATUS_APPROVED, STATUS_PUBLISHED = range(3) STATUS_CHOICES = ( (STATUS_DRAFT, _('Draft')), (STATUS_APPROVED, _('Approved')), (STATUS_PUBLISHED, _('Published')) ) title = models.CharField(max_length=255) text = models.TextField() status = models.PositiveSmallIntegerField( choices=STATUS_CHOICES, default=STATUS_DRAFT )
  • 5. sunscrapers.comYour favored tech partner. BL: Approving and Publishing class Post(Model): ... def approve(self): self.status = Post.STATUS_APPROVED self.save() def publish(self): if self.status != Post.STATUS_APPROVED: raise PostInvalidStatusError() self.status = Post.STATUS_APPROVED self.save()
  • 6. sunscrapers.comYour favored tech partner. Pros: ● Testable; ● Readable; ● DRY? Cons: ● Unmaintanable in a large code base; ● Leads to unoptimised solutions. Idea 1: Fat Models
  • 7. sunscrapers.comYour favored tech partner. Idea 2: Forms/Views/Serializers
  • 9. sunscrapers.comYour favored tech partner. Idea 3: Services
  • 10. sunscrapers.comYour favored tech partner. BL: Approving and Publishing def approve_post(post): post.status = Post.STATUS_APPROVED post.save() def publish_post(post): if post.status != Post.STATUS_APPROVED: raise PostInvalidStatusError() post.status = Post.STATUS_APPROVED post.save()
  • 11. sunscrapers.comYour favored tech partner. Pros: ● Testable; ● Readable?; ● DRY Cons: ● Unstructured in a large code base; ● Can lead to unoptimised solutions. Idea 3: Services
  • 12. sunscrapers.comYour favored tech partner. Idea 4: QuerySets/Managers
  • 13. sunscrapers.comYour favored tech partner. BL: Approving and Publishing class PostQuerySet(QuerySet): def approve(self): return self.update(status=Post.STATUS_APPROVED) def publish(self): return self.filter(status=Post.STATUS_APPROVED).update( status=Post.STATUS_PUBLISHED) class Post(Model): ... objects = PostQuerySet.as_manager()
  • 14. sunscrapers.comYour favored tech partner. Pros: ● Testable; ● Readable; ● DRY; ● Optimised (unless you do something stupid). Cons: ● Checking Business Logic rules is more complicated. ● Integrations get more difficult. Idea 4: QuerySets/Managers
  • 15. sunscrapers.comYour favored tech partner. Business Logic Rules def publish(self): return self.filter(status=Post.STATUS_APPROVED).update( status=Post.STATUS_PUBLISHED) def publish(self): if self.exclude(status=Post.STATUS_APPROVED).exists(): raise PostInvalidStatusError() return self.update(status=Post.STATUS_PUBLISHED)
  • 16. sunscrapers.comYour favored tech partner. Integrations def pay(self): Posts_data = … pay_service = PayService() try: pay_service.pay_batch(posts_data) return self.update (status=Post.STATUS_PAID) except …: ...
  • 17. sunscrapers.comYour favored tech partner. Thanks! Questions?