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.
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()
17. Connect Us @Connect Us @
www.mindfiresolutions.com
https://www.facebook.com/MindfireSolutions
http://www.linkedin.com/company/mindfire-solutions
http://twitter.com/mindfires