Python 3x Pandas Django

Django Models


A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table.

The basics:

• Each model is a Python class that subclasses django.db.models.Model.

• Each attribute of the model represents a database field.

• With all of this, Django gives you an automatically-generated database-access API.

Let’s learn by example.

In this tutorial session, we’ll see the creation of a basic poll application.

It’ll consist of two parts:

• A public site that lets people view polls and vote in them.

• An admin site that lets you add, change, and delete polls.

Let’s create a polls app, make sure you’re in the same directory as manage.py and type this command: (Quit the server with CTRL-BREAK if it’s running)

python manage.py startapp polls

That’ll create a directory polls, which is laid out like this:

  myfirstsite /
      helloworld/
      myfirstsite /
      polls/
  	  migrations/
            __init__.py
      	  __init__.py
         admin.py
         apps.py
         models.py
         tests.py
         views.py
  	db.sqlite3
  	manage.py

Creating models:

In our poll app, we’ll create two models: Question and Choice.

• A Question has a question and a publication date.

• A Choice has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question.

These concepts are represented by Python classes. Edit the polls/models.py file so it looks like this

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date      = models.DateTimeField('date published')

class Choice(models.Model):
    question    = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes       = models.IntegerField(default=0)

You can find the complete Django model field reference from https://docs.djangoproject.com/en/3.2/ref/models/fields/

Here, each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.

Here, each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.

The name of each Field instance (e.g. question_text or pub_date) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.

Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.

NOTES:

You can find more detail about Django Char Field arguments from https://docs.djangoproject.com/en/3.2/ref/models/fields/#charfield

You can find more detail about Django Integer Field arguments from https://docs.djangoproject.com/en/3.2/ref/models/fields/#integerfield

You can find more detail about Django Date Time Field arguments from https://docs.djangoproject.com/en/3.2/ref/models/fields/#datetimefield

A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Question. Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one. (We will see each database relationships concept in the upcoming sessions)

Activating models:

That small bit of model code gives Django a lot of information. With it, Django is able to:

• Create a database schema (CREATE TABLE statements) for this polls app.

• Create a Python database-access API for accessing Question and Choice objects.

But first we need to tell our myfirstproject project that the polls app is installed.

To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path is 'polls.apps.PollsConfig'. Edit the myfirstsite/settings.py file and add that dotted path to the INSTALLED_APPS setting. It’ll look like this (Highlighted in Yellow):

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

You could see PollsConfig class is in the polls/apps.py file.

image

Now Django knows to include the polls app. Let’s run another command:

python manage.py makemigrations polls

You should see something similar to the following:

(tutorial1-env) C:\Users\user\tutorial1>python manage.py makemigrations polls
Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Question
    - Create model Choice

By running makemigrations, you’re telling Django that you’ve made some changes to your models and that you’d like the changes to be stored as a migration.

Migrations are how Django stores changes to your models - they’re files on disk. You can read the migration for your new model if you like; it’s the file polls/migrations/0001_initial.py. They’re designed to be human-editable in case you want to manually tweak how Django changes things.

image

There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, run the following command to create those model tables in your database:

python manage.py migrate

You should see something similar to the following:

(tutorial1-env) C:\Users\user\tutorial1>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

The migrate command takes all the migrations that haven’t been applied and runs them against your database and synchronizing the changes you made to your models with the schema in the database.

Migrations are very powerful and let you change your models over time, as you develop your project, without the need to delete your database or tables and make new ones - it specializes in upgrading your database live, without losing data. We’ll cover them in more depth in a later part of the tutorial,

but for now, remember the three-step guide to making model changes:

• Change your models (in models.py).

• Run python manage.py makemigrations to create migrations for those changes

• Run python manage.py migrate to apply those changes to the database.

Start the development server

The Django admin site is activated by default. Let’s start the development server and explore it.

If the server is not running start it like so: python manage.py runserver

Now, open a Web browser and go to http://127.0.0.1:8000/admin/ and logging in with the superuser account you created in the previous tutorial session.

But where’s our polls app model migrations in database? It’s not displayed on the admin index page. But you should see a few types of editable content: groups and users. They are provided by django.contrib.auth, the authentication framework shipped by Django.

We need to tell the admin that Question objects have an admin interface. To do this, open the polls/admin.py file, and edit it to look like this:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

image

Now, you can see our polls app in Admin Site.

image

let’s play and explore with your admin interface.

Click “Questions”. Now you’re at the “change list” page for questions.

1. This page displays all the questions in the database and lets you choose one to change it.

2. And this page is also allowing you to add a new question.


By taking below execises, you can perform a CRUD Operations in Admin Site

Exercise 1: Create a question “What is your dream holiday destination?” by clicking + Add

Exercise 2: Update a question “What’s your dream holiday destination?” from the page displays all the questions in the Polls database and lets you choose one to change it.

Exercise 3: Delete the questions by clicking Delete button and add it again.

HINT:

image

Exercise 4: Now, it’s a time to add Choice table to our database.

To do that, we need to tell the admin that Choice objects have an admin interface.

HINT: Open the polls/admin.py file, and add the following line: admin.site.register(Choice) to see our choice table in Admin Interface.

Now, polls/admin.py look like this:

image

Exercise 5: Perform a CRUD operation for Choice table to our database.

Give the Question a couple of Choices.

1. New Zealand

2. London

3. Maldives

4. United States

HINT:

Step1: Choose the Question object from the given drop down menu and add your choice text “New Zealand” for column Choice text.

image

Wait a minute. < Question: Question object (1) > isn’t a helpful representation of this object. We are not sure about the exact question object text and will make us more confusion on choosing the right object when we have multiple Question Objects in the table.

Let’s fix that by editing the polls model (in the polls/models.py file) and adding a __str__() method to both Question and Choice:

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

and the file polls/models.py look like this:

image

And the results are:

image
image

It’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.

Let’s also add a custom method to this model: polls/models.py

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    # ...
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

let us check the use case of this function was_published_recently with an example in the upcoming session.

Congratulations! You have successfully completed Django Polls admin Interface tutorial session. Let us move to the next topic Django Views.

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!