Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Django-Queryset

613 views

Published on

This presentation covers how to perform the CRUD operation of database using Django Query-set API. The topics covered includes Creating new objects, Saving changes to existing objects, Retrieving objects from DB, Deleting objects & Complex lookups with Q objects.

Published in: Software
  • Login to see the comments

Django-Queryset

  1. 1. QuerySets Presenter: Ashok Kumar Samantray, Mindfire Solutions Date: 26/02/2015
  2. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 13. Some QuerySet methodsSome QuerySet methods - values() - values_list() - distinct() - only() - defer()
  14. 14. Presenter: Ashok Kumar Samantray, Mindfire Solutions Question and Answer
  15. 15. References LinkReferences Link https://docs.djangoproject.com/en/1.7/topics/db/models/
  16. 16. Presenter: Ashok Kumar Samantray, Mindfire Solutions Thank you
  17. 17. Connect Us @Connect Us @ www.mindfiresolutions.com https://www.facebook.com/MindfireSolutions http://www.linkedin.com/company/mindfire-solutions http://twitter.com/mindfires

×