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.
Creating ObjectsCreating Objects
Instance of a model class represents a record in DB
Instanciate a model class using the keyword argument to create an
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
Saving a ManyToMany field works a little different
– from blog.models import Author
– joe = Author.objects.create(name="Joe")
Retrieving ObjectsRetrieving Objects
Lets start with a simple select query
– all_entries = Entry.objects.all()
Add conditions using the filter(**kwargs), exclude(**kwargs)
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
– 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
Negative indexing is not supported
Use of step parameter is allowed and it evaluates the querysets
order_by() is used for order the result
Field LookupsField Lookups
It provides the conditions for where clause in the query
Used in the Queryset methods as keyword arguments filter(),
How does it look?
– Field name and lookuptype joined with a double
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
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
~Q is used to negate(NOT) the query.
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