SlideShare una empresa de Scribd logo
1 de 17
QuerySets
Presenter: Ashok Kumar Samantray, Mindfire
Solutions
Date: 26/02/2015
Presenter: Ashok Kumar Samantray, Mindfire
Solutions
About me
Connect Me:
Facebook: https://www.facebook.com/ashokkumar.samantaray.50
Linkedin: https://www.linkedin.com/in/ashokkumarsamantray
Google+: https://plus.google.com/+AshokKumarSamantray117/
Contact Me:
Email: ashok.samantray@mindfiresolutions.com, mailashok117@gmail.com
Skype: mfsi_ashok
Ashok Kumar Samantray
Python Developer
Skills: Python, Django, Tastypie,
MySQL, PostgreSQL, MongoDB,
JQuery, JavaScript, AJAX
Creating Objects
Saving Changes to Objects
Retrieving Objects
Deleting Objects
Complex Lookups with Q Objects
Q&A
AgendaAgenda
Presenter: Ashok Kumar Samantray, Mindfire
Solutions
Creating ObjectsCreating Objects
Instance of a model class represents a record in DB
Instanciate a model class using the keyword argument to create an
object.
Instanciation generates an INSERT query.
Call the save() explicitly to run the query.
Insert record using the create(), get_or_create() in single step.
Saving Changes to ObjectsSaving Changes to Objects
To save changes to the record already present in the DB use save()
Save() performs the update query behind the scenes
Saving a Foreignkey works by assigning the object of the right
model instance.
Saving a ManyToMany field works a little different
– from blog.models import Author
– joe = Author.objects.create(name="Joe")
– entry.authors.add(joe)
Retrieving ObjectsRetrieving Objects
Lets start with a simple select query
– all_entries = Entry.objects.all()
Add conditions using the filter(**kwargs), exclude(**kwargs)
– Entry.objects.filter(pub_date__year=2006)
– Entry.objects.exclude(pub_date__year=2006)
Retrieving Objects(cont.)Retrieving Objects(cont.)
Retrieving a single object with get()
– Get() works on unique object
– It returns the object directly
– Raise MultipleObjectsReturned error if more than one item
retrieved
– e.g.: one_entry = Entry.objects.get(pk=1)
Limit, Offset and OrderingLimit, Offset and Ordering
A Queryset is iterable.
Queryset can be sliced like all other iterables
Limit and Offset by slicing the queryset
e.g.:- Entry.objects.all()[5:10]
Negative indexing is not supported
e.g:- Entry.objects.all()[-1]
Use of step parameter is allowed and it evaluates the querysets
order_by() is used for order the result
e.g:- Entry.objects.order_by('headline')
Field LookupsField Lookups
It provides the conditions for where clause in the query
Used in the Queryset methods as keyword arguments filter(),
exclude(), get().
How does it look?
– field__lookuptype=value
– Field name and lookuptype joined with a double
underscore
e.g.: - Entry.objects.filter(pub_date__lte='2006-01-01')
Few lookuptypes are exact, iexact, contains etc.
Lookup that span relationshipsLookup that span relationships
This performs the join operations.
Use the field name of related fields across models, separated by
double underscores
e.g.: - Entry.objects.filter(blog__name='Beatles Blog')
Complex lookups with Q objectsComplex lookups with Q objects
Keyword arguments used in filter() performs AND operation.
Q objects comes to rescue for more complex query with OR
statements.
~Q is used to negate(NOT) the query.
e.g.: -
Poll.objects.get(
Q(question__startswith='Who'),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005,5, 6))
Deleting ObjectsDeleting Objects
Delete() is used for deleting records from the DB
This immediately deletes the object
Method has no return value
e.g.:- Entry.objects.filter(pub_date__year=2005).delete()
Some QuerySet methodsSome QuerySet methods
- values()
- values_list()
- distinct()
- only()
- defer()
Presenter: Ashok Kumar Samantray, Mindfire
Solutions
Question and
Answer
References LinkReferences Link
https://docs.djangoproject.com/en/1.7/topics/db/models/
Presenter: Ashok Kumar Samantray, Mindfire
Solutions
Thank you
Connect Us @Connect Us @
www.mindfiresolutions.com
https://www.facebook.com/MindfireSolutions
http://www.linkedin.com/company/mindfire-solutions
http://twitter.com/mindfires

Más contenido relacionado

Destacado

The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyTzu-ping Chung
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘Jiho Lee
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesDjango - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesMarkus Zapke-Gründemann
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia ContiniWEBdeBS
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework  for perfectionists with deadlinesDjango - The Web framework  for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesMarkus Zapke-Gründemann
 
NoSql Day - Apertura
NoSql Day - AperturaNoSql Day - Apertura
NoSql Day - AperturaWEBdeBS
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_WEBdeBS
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - ChiusuraWEBdeBS
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 Na Lee
 

Destacado (20)

The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.py
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Html5 History-API
Html5 History-APIHtml5 History-API
Html5 History-API
 
PyClab.__init__(self)
PyClab.__init__(self)PyClab.__init__(self)
PyClab.__init__(self)
 
라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘
 
PythonBrasil[8] closing
PythonBrasil[8] closingPythonBrasil[8] closing
PythonBrasil[8] closing
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesDjango - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlines
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia Contini
 
User-centered open source
User-centered open sourceUser-centered open source
User-centered open source
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework  for perfectionists with deadlinesDjango - The Web framework  for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlines
 
Digesting jQuery
Digesting jQueryDigesting jQuery
Digesting jQuery
 
NoSql Day - Apertura
NoSql Day - AperturaNoSql Day - Apertura
NoSql Day - Apertura
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - Chiusura
 
Bottle - Python Web Microframework
Bottle - Python Web MicroframeworkBottle - Python Web Microframework
Bottle - Python Web Microframework
 
Load testing
Load testingLoad testing
Load testing
 
Website optimization
Website optimizationWebsite optimization
Website optimization
 
EuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein RückblickEuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein Rückblick
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论
 

Similar a Django-Queryset

Ektron London Conference: New Search Features in Ektron 9
Ektron London Conference: New Search Features in Ektron 9Ektron London Conference: New Search Features in Ektron 9
Ektron London Conference: New Search Features in Ektron 9Ektron
 
Writing Code To Interact With Enterprise Search
Writing Code To Interact With Enterprise SearchWriting Code To Interact With Enterprise Search
Writing Code To Interact With Enterprise SearchCorey Roth
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)MongoDB
 
Search page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-netSearch page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-netsonia merchant
 
Building A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- IIBuilding A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- IIPooja Gaikwad
 
Introduction to whats new in css3
Introduction to whats new in css3Introduction to whats new in css3
Introduction to whats new in css3Usman Mehmood
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In PyEric ShangKuan
 
Sumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced AnalyticsSumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced AnalyticsSumo Logic
 
Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...
Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...
Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...Mahmoud Hamed Mahmoud
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JSAkshay Mathur
 
Solr Search Engine: Optimize Is (Not) Bad for You
Solr Search Engine: Optimize Is (Not) Bad for YouSolr Search Engine: Optimize Is (Not) Bad for You
Solr Search Engine: Optimize Is (Not) Bad for YouSematext Group, Inc.
 
SPCA2013 - SharePoint Nightmares - Coding Patterns and Practices
SPCA2013 - SharePoint Nightmares - Coding Patterns and PracticesSPCA2013 - SharePoint Nightmares - Coding Patterns and Practices
SPCA2013 - SharePoint Nightmares - Coding Patterns and PracticesNCCOMMS
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012Yaqi Zhao
 
Testing RESTful web services with REST Assured
Testing RESTful web services with REST AssuredTesting RESTful web services with REST Assured
Testing RESTful web services with REST AssuredBas Dijkstra
 
Spsvb Developer Intro to SharePoint Search
Spsvb   Developer Intro to SharePoint SearchSpsvb   Developer Intro to SharePoint Search
Spsvb Developer Intro to SharePoint SearchMichael Oryszak
 

Similar a Django-Queryset (20)

Ektron London Conference: New Search Features in Ektron 9
Ektron London Conference: New Search Features in Ektron 9Ektron London Conference: New Search Features in Ektron 9
Ektron London Conference: New Search Features in Ektron 9
 
Writing Code To Interact With Enterprise Search
Writing Code To Interact With Enterprise SearchWriting Code To Interact With Enterprise Search
Writing Code To Interact With Enterprise Search
 
Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)Indexing and Query Optimizer (Mongo Austin)
Indexing and Query Optimizer (Mongo Austin)
 
Search page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-netSearch page-with-elasticsearch-and-dot-net
Search page-with-elasticsearch-and-dot-net
 
Building A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- IIBuilding A Search Page with Elasticsearch and .NET- II
Building A Search Page with Elasticsearch and .NET- II
 
Java scriptforjavadev part2a
Java scriptforjavadev part2aJava scriptforjavadev part2a
Java scriptforjavadev part2a
 
Introduction to whats new in css3
Introduction to whats new in css3Introduction to whats new in css3
Introduction to whats new in css3
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
 
Struts 2
Struts 2Struts 2
Struts 2
 
Sumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced AnalyticsSumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced Analytics
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...
Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...
Exam 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions Le...
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
 
Solr Search Engine: Optimize Is (Not) Bad for You
Solr Search Engine: Optimize Is (Not) Bad for YouSolr Search Engine: Optimize Is (Not) Bad for You
Solr Search Engine: Optimize Is (Not) Bad for You
 
PHP with MYSQL
PHP with MYSQLPHP with MYSQL
PHP with MYSQL
 
SPCA2013 - SharePoint Nightmares - Coding Patterns and Practices
SPCA2013 - SharePoint Nightmares - Coding Patterns and PracticesSPCA2013 - SharePoint Nightmares - Coding Patterns and Practices
SPCA2013 - SharePoint Nightmares - Coding Patterns and Practices
 
Pyconie 2012
Pyconie 2012Pyconie 2012
Pyconie 2012
 
Testing RESTful web services with REST Assured
Testing RESTful web services with REST AssuredTesting RESTful web services with REST Assured
Testing RESTful web services with REST Assured
 
Django Models
Django ModelsDjango Models
Django Models
 
Spsvb Developer Intro to SharePoint Search
Spsvb   Developer Intro to SharePoint SearchSpsvb   Developer Intro to SharePoint Search
Spsvb Developer Intro to SharePoint Search
 

Más de Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
 
diet management app
diet management appdiet management app
diet management app
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
 
ELMAH
ELMAHELMAH
ELMAH
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
 

Último

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Último (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

Django-Queryset

  • 1. QuerySets Presenter: Ashok Kumar Samantray, Mindfire Solutions Date: 26/02/2015
  • 2. Presenter: Ashok Kumar Samantray, Mindfire Solutions About me Connect Me: Facebook: https://www.facebook.com/ashokkumar.samantaray.50 Linkedin: https://www.linkedin.com/in/ashokkumarsamantray Google+: https://plus.google.com/+AshokKumarSamantray117/ Contact Me: Email: ashok.samantray@mindfiresolutions.com, mailashok117@gmail.com Skype: mfsi_ashok Ashok Kumar Samantray Python Developer Skills: Python, Django, Tastypie, MySQL, PostgreSQL, MongoDB, JQuery, JavaScript, AJAX
  • 3. Creating Objects Saving Changes to Objects Retrieving Objects Deleting Objects Complex Lookups with Q Objects Q&A AgendaAgenda Presenter: Ashok Kumar Samantray, Mindfire Solutions
  • 4. Creating ObjectsCreating Objects Instance of a model class represents a record in DB Instanciate a model class using the keyword argument to create an object. Instanciation generates an INSERT query. Call the save() explicitly to run the query. Insert record using the create(), get_or_create() in single step.
  • 5. Saving Changes to ObjectsSaving Changes to Objects To save changes to the record already present in the DB use save() Save() performs the update query behind the scenes Saving a Foreignkey works by assigning the object of the right model instance. Saving a ManyToMany field works a little different – from blog.models import Author – joe = Author.objects.create(name="Joe") – entry.authors.add(joe)
  • 6. Retrieving ObjectsRetrieving Objects Lets start with a simple select query – all_entries = Entry.objects.all() Add conditions using the filter(**kwargs), exclude(**kwargs) – Entry.objects.filter(pub_date__year=2006) – Entry.objects.exclude(pub_date__year=2006)
  • 7. Retrieving Objects(cont.)Retrieving Objects(cont.) Retrieving a single object with get() – Get() works on unique object – It returns the object directly – Raise MultipleObjectsReturned error if more than one item retrieved – e.g.: one_entry = Entry.objects.get(pk=1)
  • 8. Limit, Offset and OrderingLimit, Offset and Ordering A Queryset is iterable. Queryset can be sliced like all other iterables Limit and Offset by slicing the queryset e.g.:- Entry.objects.all()[5:10] Negative indexing is not supported e.g:- Entry.objects.all()[-1] Use of step parameter is allowed and it evaluates the querysets order_by() is used for order the result e.g:- Entry.objects.order_by('headline')
  • 9. Field LookupsField Lookups It provides the conditions for where clause in the query Used in the Queryset methods as keyword arguments filter(), exclude(), get(). How does it look? – field__lookuptype=value – Field name and lookuptype joined with a double underscore e.g.: - Entry.objects.filter(pub_date__lte='2006-01-01') Few lookuptypes are exact, iexact, contains etc.
  • 10. Lookup that span relationshipsLookup that span relationships This performs the join operations. Use the field name of related fields across models, separated by double underscores e.g.: - Entry.objects.filter(blog__name='Beatles Blog')
  • 11. Complex lookups with Q objectsComplex lookups with Q objects Keyword arguments used in filter() performs AND operation. Q objects comes to rescue for more complex query with OR statements. ~Q is used to negate(NOT) the query. e.g.: - Poll.objects.get( Q(question__startswith='Who'), Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005,5, 6))
  • 12. Deleting ObjectsDeleting Objects Delete() is used for deleting records from the DB This immediately deletes the object Method has no return value e.g.:- Entry.objects.filter(pub_date__year=2005).delete()
  • 13. Some QuerySet methodsSome QuerySet methods - values() - values_list() - distinct() - only() - defer()
  • 14. Presenter: Ashok Kumar Samantray, Mindfire Solutions Question and Answer
  • 16. Presenter: Ashok Kumar Samantray, Mindfire Solutions Thank you
  • 17. Connect Us @Connect Us @ www.mindfiresolutions.com https://www.facebook.com/MindfireSolutions http://www.linkedin.com/company/mindfire-solutions http://twitter.com/mindfires