Change Database Setting
Open up mysite/settings.py
, find snippet as blew:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Here you can change your database to others if needed
* ENGINE – Either ‘django.db.backends.sqlite3’, ‘django.db.backends.postgresql’, ‘django.db.backends.mysql’, or ‘django.db.backends.oracle’.
* NAME – Name of database
We can aslo change the time zone in the setting file
TIME_ZONE = 'America/Chicago'
To create related tables in the database, we need to execute
python manage.py migrate
. It will create tables following by INSTALLED_APPS
in setting.py
.
To read the recetly created tables in sqlite:
python manage.py dbshell
# into sqlite shell
.table
Thre result will like blew:
sqlite> .tables
auth_group auth_user_user_permissions
auth_group_permissions django_admin_log
auth_permission django_content_type
auth_user django_migrations
auth_user_groups django_session
Create a model
In offical defination, model
is the single, definitive source of truth about your data.
. In my option, model is only data model
in single place, rather than in database as well as in you codes.
Let copy this into webapp/models.py
. We create two classes which are also two tables in the database. Each variable is a filename with its data type, such as models.CharField
is type char, and models.DataTimeField
is datatime. Here we can also figure out a ForeignKey in class Choice
which points to Question
.
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
To active model, we need to add config file into INSTALLED_APPS
. webapp.apps.WebappConfig
means calling WebappConfig in apps file in webapp folder.
INSTALLED_APPS = [
'webapp.apps.WebappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Then we run makemigrations
to create migration files.
python manage.py makemigrations webapp
# then you will see somehitng like the following:
Migrations for 'webapp':
webapp/migrations/0001_initial.py
- Create model Choice
- Create model Question
- Add field question to choice
We can find the migration opertaion in webapp/migrations/
, we run python manage.py migrate
, then we can find two new table in the database already(.schema {tablename}
)
Summary 3 steps for 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.
Play with Shell to add some records into db
To get into the shell, we need to execute
python manage.py shell
Then add some questions and choice
from webapp.models import Choice, Question
# show all question
Question.objects.all()
# add a new question
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
# save into database
q.save()
q.id()
# search in database, similar to where in sql
Question.objects.filter(id=1) # id=1
Question.objects.filter(question_text__startswith='What')
Question.objects.get(pk=1) # filter with pk
# add some choices, here Django creates a set to hold the "other side" of ForeignKey relation
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
q.choice_set.create(choice_text='The moon', votes=0)
# delete records
d = q.choice_set.filter(choice_text__startswith='The moon')
d.delete()
Django Admin
To create a admin with python manage.py createsuperuser
, then system will ask you enter the username, email and password. After this, we can access admin website http://localhost:8000/admin/
If admin account want to add new question in the website, we need to add the follow snippet into admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
Some issue
When I tried to save question in the admin webpage, there poped out a issue like no such table: main.auth_user__old
. Just marked here waiting to find the reason later.
Leave a Reply