Building a Django project from scratch (part 1)
Database Configuration
Django supports the following databases:
‘django. Db. Backends. Sqlite3’, ‘the django. Db. Backends. Postgresql’, ‘the django. Db. Backends. Mysql’, or ‘django. Db. Backends. Oracle’.
Using mysql as an example, modify the Settings Settings as follows (to the database you want to connect to) and install the mysqlClient library
. DATABASES = {'default': {
'ENGINE': 'django.db.backends.mysql'.# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'NAME': 'demo001'.'USER': 'root'.'PASSWORD': 'pwd'.'HOST': '127.0.0.1'.'PORT': 3306}}...Copy the code
After the modification is complete, start the service. If the service is successfully started, the configuration is ok
Create the model
A model is defined to define and describe the database library tables in Python code
Follow the example below to edit the polls/models.py file:
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)
Copy the code
Each Field is an instance of the Field class – for example, a character Field is represented as a CharField, and a DateTimeField as a DateTimeField. This tells Django what type of data to process for each field.
The name of each Field class instance variable (such as question_TEXT or pub_date) is also the Field name, so it’s best to use a machine-friendly format. You’ll use them in Python code, and the database will use them as column names.
* Primary keys (IDs) are created automatically. (Of course, you can customize it.)
Application model
Step 1
First include the application in the project, setting it in Settings as follows
INSTALLED_APPS = [
'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'polls',]Copy the code
Step 2
In the second step, the model generates Python code for manipulating the database
$ python manage.py makemigrations polls
Copy the code
The output is as follows
Migrations for 'polls':
polls/migrations/0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
Copy the code
You can use the following command to view the SQL statement to be executed
$ python manage.py sqlmigrate polls 0001
Copy the code
The output is as follows
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
"id" serial NOT NULL PRIMARY KEY,
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL
);
--
-- Create model Question
--
CREATE TABLE "polls_question" (
"id" serial NOT NULL PRIMARY KEY,
"question_text" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
ALTER TABLE "polls_choice"
ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"
FOREIGN KEY ("question_id")
REFERENCES "polls_question" ("id")
DEFERRABLE INITIALLY DEFERRED;
COMMIT;
Copy the code
Step 3
Actually applying the model to the database
$ python manage.py migrate
Copy the code
The migrate command selects all migrations that have not yet been performed (Django keeps track of which migrations have been performed by creating a special table django_migrations in the database) and applies them to the database – that is, synchronizing your changes to the model to the database structure.
conclusion
- Edit the models.py file to change the model.
- Run Python Manage. py Makemigrations to generate migration files for model changes.
- Run Python manage.py Migrate to apply the database migration.
Django Shell
You can enter Djangos interactive command line mode as follows. You need to do this because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, This variable lets Django set the import path for Python packages based on the mysite/settings.py file.
$ python manage.py shell
Copy the code
After entering the interactive command line
>>> from polls.models import Choice, Question # Import the model
# query all data
>>> Question.objects.all()
<QuerySet []>
# create data
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
# view current data (increment id is generated only after save)
>>> q.id
1
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012.2.26.13.0.0.775217, tzinfo=<UTC>)
Modify the data and save it again
>>> q.question_text = "What's up?"
>>> q.save()
Query all data again
>>> Question.objects.all()
<QuerySet [<Question: Question object (1) > >]Copy the code
View the data
>
class Question(models.Model) :
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self) :
return str(self.id) + ':' +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
Copy the code
Go into the Django Shell again and look at the data
>>> from polls.models import Choice,Question
>>> Question.objects.all()
<QuerySet [<Question: 1:test ques001>]>
Copy the code
* Refer to the Official Django documentation for more information about the query API
Django Admin
Creating an Administrator Account
$python manage.py createsuperuser # Interactive input corresponding information $python manage.py runserver # start the serviceCopy the code
Open the “http://127.0.0.1:8000/admin/” login admin management interface
Add an application to the management console
Open polls/admin.py and add the following code
from django.contrib import admin
from .models import Question
admin.site.register(Question)
Copy the code
Restart the service. The management console page is as follows
* See the Official Django documentation for more information about admin operations