PART -7

This chapter will teach you the following:

  • Using the Django ORM to query the database and filter through results
  • Applying migrations to database

Once you’ve created a model, Django automatically provides a high-level Python API for working with those models.

You can check the raw sql for the table created using

python manage.py sqlmigrate <appname> migration number

or

python manage.py sqlmigrate blogapp 0001 , which gives us

To learn how to use Django’s database API, we’re going to be using the Django interactive shell. Django’s interactive shell runs just like the regular Python interactive shell. Try it out by running python manage.py shell and typing the following:

The first 2 lines import the Post and User model

Retrieving all objects

The all()method returns a Queryset of all the objects in the database.

Creating objects

This performs an INSERT SQL statement behind the scenes. Django doesn’t hit the database until you explicitly call save().

Running the Post.objects.all() now will return

You can now get all the fields of the particular like this..

Retrieving a single object with get()

returns the first object which have primary key as 1

Related objects

When you define a relationship in a model (i.e., a ForeignKey, OneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related objects.

Django also creates API accessors for the “other” side of the relationship — the link from the related model to the model that defines the relationship.

the .model_set (or ) x.post_set.all() returns all the posts of the user (if it has the relationship)

creates a new post for the user in the Post model

Retrieving specific objects with filters

To create a subset of a QuerySet, you refine the initial QuerySet, adding filter conditions. The two most common ways to refine a QuerySet are:

filter(**kwargs)Returns a new QuerySet containing objects that match the given lookup parameters.exclude(**kwargs)Returns a new QuerySet containing objects that do not match the given lookup parameters.

Now let’s filter using other attributes of the model.

The first is a base Queryset containing all entries that contain a headline starting with “Making A Web”. The second is a subset of the first, with an additional criteria that excludes records whose date_posted is today or in the future (greater than or equal to) .The third excludes the post which have ‘building’ in it’s content (i for case insensitive)

Deleting objects

The delete method, conveniently, is named delete(). This method immediately deletes the object and returns the number of objects deleted and a dictionary with the number of deletions per object type.

Let’s now set the home function in views.py to as follows,

And home.html to..

Next Up..

Previously…

Posting Django Tutorials with Beginner to Advanced Projects