Django Learning (1) from build to database operations

Source: Internet
Author: User

Basic translation of the official tutorials

Django-admin Startproject MySite
command to create a project

Take a look at the Django structure diagram. multiple ways to interact with engineering
Inner Mysilte is a package that requires import
init. PY is defined here as the PY package settings statement? Web Server Gateway Interface

Python migrate is probably a configuration.
Then there is
Python runserver but not (estimated to be a set problem)
And then
Python runserver
You will have access to the

The web app can be anywhere in Python path again
Here we create a sibling directory in
$ python Startapp polls
Edit File
From django.http import HttpResponse
def index (Request):
Return HttpResponse ("Hello, World.") You ' re at the polls index. ")
After creating the simplest views, you need to map it to the URL

Set up in the same directory

from django.conf.urls import urlfrom . import viewsurlpatterns = [    url(r‘^$‘, views.index, name=‘index‘),]

Then point to Polls.urls in the global URL


from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [    url(r‘^polls/‘, include(‘polls.urls‘)),    url(r‘^admin/‘,,]

Note the ^ symbol because the Include function does not eat $
Using include allows you to place URLs in various locations without having to put a piece
It is worth mentioning that the only exception is

We are using the URL function to establish a link to the map to URL
URL function:
Regex string
String used for matching

If a match is made to the regex, the specified view function is called.
Use HttpRequest as the first argument, and the character to be matched as other arguments
If the regex uses simple captures, values is passed as positional arguments; If it uses named captures, values are passed as keyword arguments. We ' ll give an example of the this in a bit.
I can't read it, but there's an example behind it.

In the dictionary, Tutoril doesn't introduce

A string
Specify an unambiguous name for the URL so that the URL patterns can be modified globally

Part2 Linked Database

Configuration database
MySQL was previously installed
Now that you have installed the
Install mysqlclient times wrong oserror:mysql_config not found
The reason is that there is no installation: Libmysqlclient-dev
sudo apt-get install Libmysqlclient-dev
Find the path to the Mysql_config file
sudo updatedb
Locate Mysql_config
Mysql_config is located at:/usr/bin/mysql_config
Not installed according to[email protected]/blog/static/6669335020161260025544/Source Package
Just a direct PIP installed

Configuration file
The main part of database is to add some parameters

I'm dead again. mysql port changed from default 3306 to 6666
It's mainly two port settings inside the/ETC/MYSQL/MY/CNF.

And then run service MySQL start.

When you run the server, you must first
Python Migration

Then added "polls" in Installed_app in
Python migration is actually the process of taking the configuration in into effect

And then modifying the under polls is probably what the database model means.
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)
Each class is a subclass of a Django.db.models.Model
Called model

The Variables (field sub-class under models) for each model corresponds to an item in the database
You'll use this value in your Python code, and your database would use it as the column name.
Each model corresponds to a table in the database
But to make them effective, they must first
Python makemigrations
Python Migrate
A variable of each Field type can specify a name,
Some require parameters, such as Charfield need a maxlength
This parameter will also be used in validation
Field can also have default values

We define a relationship with ForeignKey.
Every choic is connected to a question.
Multiple ways to link Django support databases
Many-to-many, one-to-many
The app is standalone in Django, and each app can be used by multiple projetc

In Django, it's best not to write "polls" directly in Installed_apps.
Can write on
That's it, right? Polls configuration files are transferred to the polls, very convenient
There is a Pollsconig class within the
A method that has a name returns polls
The action and appeal of the thing should be the same
Python makemigrations Polls

By running Makemigrations, your ' re telling Django that's you ' ve made some changes to your models (in this case, you've made n EW ones) and that you ' d like the changes to be stored as a migration.

Makemigrations just made a change.

This file is generated in
This file can be edited manually

Migrations is how Django stores changes to your models (and thus your database schema)-they ' re just files on disk. You can read the migration for your new model if you like; It ' s the file polls/migrations/ Don ' t worry, you ' re not expected-read them every time Django makes one, but they ' re designed-be-human-editable in CA Se want to manually tweak how Django changes things.

There's a command that would run the migrations for you and manage your database schema Automatically-that ' s called Migra Te, and we'll come to it in a moment-but first, let's see how SQL that migration would run. The sqlmigrate command takes migration names and returns their SQL:

Python sqlmigrate polls 0001
This command can show migrate details.
Translated into SQL language to manipulate the database

The results of the conversion are determined by the specific database used (I guess the engine is doing it)

The name of the Table is mixed by the name of the app and the name of the model

primary keys (ID) is automatically added (can be manually modified)

Convention, Django adds _id corresponding to Forenognkey file name on fetch (can be overridden)

Database-specific filed depends on your database
It's tailored to the database you ' re using, so database-specific field types such as Auto_increment (MySQL), serial (POSTG resql), or integer primary key AutoIncrement (SQLite) is handled for you automatically. Same goes for the quoting of field names–e.g., using a double quotes or single quotes.

The sqlmigrate is not really going to do migrate just output the SQL statement so you have a number in mind

Command python check
is to check whether there is no problem in the project (do not actually do migrate or database)


Three steps to change a database file
Change your models (in
Run python makemigrations to create migrations for those changes
Run python migrate to apply those changes to the database.
The reason for this design is to make it easier for many people to develop
Read the Django-admin documentation for full information on what the utility can do.

Play with the API


Not a simple call to Python,
Because set the
Django_settings_module environment variables.
The path to the sfsite/ file can be obtained

If you don't want to do this, you can
Only need to design environment variables
Django_settings_module environment variable to mysite.settings

Must be at the same level under the
Because to make import sfsite effective

After entering the shell, you can manipulate it.
Import Django
Django.setup ()
Q = Question (question_text= "What ' s new?", ())

Save the object into the database. You have the call Save () explicitly. ()

Now it had an ID. Note that this might say "1L" instead of "1", Dependingon which the database you ' re using. That ' s no biggie; It just means yourdatabase backend prefers to return integers as Python long integerobjects.

Access model field values via Python attributes.

"What ' s new?"
Datetime.datetime (2, 0, 0, 775217, tzinfo=

Change values by changing the attributes and then calling Save ().

Q.question_text = "What's Up?" ()

Objects.all () displays all the questions in the database.

Question.objects.all ()
<queryset [

Re-punch the shell
Manipulate the database with the Django-provided API

Question.objects.all () View all
Question.objects.filter (id=1) filter
Question.objects.filter (question_text__startswith= ' what ')
Note the notation, which is represented by __ two underscores

>>> from django.utils import timezone>>> current_year = () .year>>> Question.objects.get (pub_date__year=current_year) <question:what ' s up?># Request an ID that doesn ' t exist, this Would raise an exception.>>> Question.objects.get (id=2) Traceback (most recent call last): ...  Doesnotexist:question matching query does not exist.# Lookup by a primary key was the most common case, so Django provides a# shortcut for Primary-key exact lookups.# the following are identical to Question.objects.get (id=1) .>>> questio N.objects.get (pk=1) <question:what ' s up?># make sure our custom method worked.>>> q = Question.objects.get (pk=1) >>> q.was_published_recently () true# Give The Question a couple of Choices. The Create call constructs a new# Choice object, does the INSERT statement, adds the Choice to the set# of available choic ES and returns the new Choice object. Django creates# A set to hold the "other side" of a ForeiGnkey relation# (e.g. a question ' s choice) which can be accessed via the api.>>> q = Question.objects.get (pk=1) # Display any choices from the related object set – none so Far.>>> q.choice_set.all () <queryset []># Create Three choices.>>> q.choice_set.create (choice_text= ' Not much ', votes=0) <choice:not much>>>> Q.choice_set.create (choice_text= ' The sky ', votes=0) <choice:the sky>>>> C = q.choice_set.create (choice _text= ' Just hacking again ', votes=0) # Choice objects has API access to their related Question objects.>>> c.ques Tion<question:what ' s up?># and Vice Versa:question objects get access to Choice objects.>>> Q.choice_set. All () <queryset [<choice:not much>, <choice:the Sky>, <choice:just hacking again>]>>> > Q.choice_set.count () 3# the API automatically follows relationships as far as your need.# use double underscores to Sep Arate relationships.# This works as many Levels deep as you want; There ' s no limit.# Find all Choices for any question whose pub_date are in this year# (reusing ' current_year ' variable We created above) .>>> Choice.objects.filter (question__pub_date__year=current_year) <queryset [< Choice:not much>, <choice:the Sky>, <choice:just hacking again>]># Let's delete one of the choices. Use Delete () for that.>>> C = q.choice_set.filter (choice_text__startswith= ' Just hacking ') >>> C.delete ()

This makes it possible to manipulate the database
is essentially a mapping of the classes inside the

Django Learning (1) from build to database operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.