Creating Django Models

Part of this chapter is based on tutorials by Django Girls Tutorial : https://tutorial.djangogirls.org

Django Models

What we want to create now is something that will store all the posts in our blog. But to be able to do that we need to talk a little bit about things called objects.

Objects

There is a concept in programming called object-oriented programming. The idea is that instead of writing everything as a boring sequence of programming instructions, we can model things and define how they interact with each other.

So what is an object? It is a collection of properties and actions. It sounds weird, but we will give you an example.

If we want to model a cat, we will create an object Cat that has some properties such as colour, age, mood (like good, bad, or sleepy ;)), and owner (which could be assigned a Person object – or maybe, in case of a stray cat, this property could be empty).

Then the Cat has some actions: purr, scratch, or feed (in which case, we will give the cat some CatFood, which could be a separate object with properties, like taste).

Cat
--------
colour
age
mood
owner
purr()
scratch()
feed(cat_food)
CatFood
--------
taste

So basically the idea is to describe real things in code with properties (called object properties) and actions (called methods).

So how do we create a model for this game? Let's keep it simple.

A game needs a player, what's that player's name? What other properties should it have?

Game
----
player
next_move
Player
------
name
lives
score

Let's start modeling it in Django!

A model in Django is a special kind of object – it is saved in thedatabase. A database is a collection of data. This is a place in which you will store information about users, your blog posts, etc. We will be using a SQLite database to store our data. This is the default Django database adapter – it'll be enough for us right now.

You can think of a model in the database as a spreadsheet with columns (fields) and rows (data).

Creating a model

In the myfirstgame/models.py file we define all objects calledModels– this is a place in which we will define our blog post.

Let's open myfirstgame/models.py, remove everything from it, and write code like this:

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

class Player(models.Model):
    name = models.CharField(max_length=200)
    score = models.IntegerField(
            blank=True, null=True)
    game_end = models.DateTimeField(
            blank=True, null=True)

    def gameover(self):
        self.game_end = timezone.now()
        self.save()

    def __str__(self):
        return self.name

Double-check that you use two underscore characters (_) on each side of str. This convention is used frequently in Python and sometimes we also call them "dunder" (short for "double-underscore").

It looks scary, right? But don't worry – we will explain what these lines mean!

All lines starting withfromorimportare lines that add some bits from other files. So instead of copying and pasting the same things in every file, we can include some parts withfrom ... import ....

class Player(models.Model): – this line defines our model (it is an object).

  • class is a special keyword that indicates that we are defining an object.
  • Post is the name of our model. We can give it a different name (but we must avoid special characters and whitespace). Always start a class name with an uppercase letter.
  • models.Model means that the Player is a Django Model, so Django knows that it should be saved in the database.

Now we define the properties we were talking about (name, score, game_end). To do that we need to define the type of each field (Is it text? A number? A date? A relation to another object, like a User?)

  • models.CharField – this is how you define text with a limited number of characters.
  • models.DateTimeField – this is a date and time.
  • models.IntegerField – this is an integer

We will not explain every bit of code here since it would take too much time. You should take a look at Django's documentation if you want to know more about Model fields and how to define things other than those described above (https://docs.djangoproject.com/en/2.0/ref/models/fields/#field-types).

What aboutdef gameover(self):? defmeans that this is a function/method and gameover is the name of the method. You can change the name of the method if you want. The naming rule is that we use lowercase and underscores instead of spaces. For example, a method that calculates average price could be calledcalculate_average_price.

Methods oftenreturnsomething. There is an example of that in the__str__method. In this scenario, when we call__str__()we will get a text (string) with a Post title.

Also notice that both def gameover(self): anddef __str__(self):are indented inside our class. Because Python is sensitive to whitespace, we need to indent our methods inside the class. Otherwise, the methods won't belong to the class, and you can get some unexpected behaviour.

If something is still not clear about models, feel free to ask your coach! We know it is complicated, especially when you learn what objects and functions are at the same time. But hopefully it looks slightly less magic for you now!

Create tables for models in your database

The last step here is to add our new model to our database. First we have to make Django know that we have some changes in our model. (We have just created it!)

Go to your console window and type the following:

$ python manage.py makemigrations myfirstgame

It will look like this:

Migrations for 'myfirstgame':
  myfirstgame/migrations/0001_initial.py
    - Create model Player

Note: Remember to save the files you edit. Otherwise, your computer will execute the previous version which might give you unexpected error messages.

Django prepared a migration file for us that we now have to apply to our database. Type the following in the console:

(myvenv)$ python manage.py migrate myfirstgame

The output should be as follows:

Operations to perform:
  Apply all migrations: myfirstgame
Running migrations:
  Applying myfirstgame.0001_initial... OK

Hurray! Our Player model is now in our database! It would be nice to see it, right?

Jump to the next chapter to see what your Player looks like!

results matching ""

    No results matching ""