Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Today in django tutorial series we define 2 models in polls/models.py. One for Question and another for Choice.
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)


Our model's parent class is django models.Model and each model has its own fields. You can define string field by CharField, integer by IntegerField and datetime by DateTimeField.

* The name of each field is the column name in the table.

* max_length can be given as an argument to put restrictions on field's length

* you can give a human readable name to each field by providing an optional first positional argument like pub_date which is set to date published

* you can define foreign keys by models.ForeignKey

* fields can have default value is we have set for votes by using default

Until now Django knows nothing about our polls app, we need to plug it in, in order to include it in our project. Go to saturn/settings.py and do as follow:
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]


Now use makemigrations command to tell Django to store new model changes in migrations folder inside of polls:
$ python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Choice
- Create model Question
- Add field question to choice


Finally use the below command to create the tables:
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying polls.0001_initial... OK


migrate is smart and just applies those changes needed, if you are careful enough you can see that a file is created that is called polls.0001_initial. This file is created by our command makemigrations in the previous step.

So we've done 2 steps overall:
1- used makemigrations to create migration files.
2- applied the migration generated in step 1 by using migrate.

#python #django #migrate #models #migrate #makemigrations #django_part5