Django learning (1) from establishment to database operation

Basically translate the official tutorial


django-admin startproject mysite
command to create a project

Let's take a look at django's structure diagram
manage.py and various ways to interact with the project
inner mysilte is the package that needs to be imported init.py is the package
that defines py here is the package
settings.py set
the urls.py declaration?
wsgi.py Web Server Gateway Interface

python manager.py migrate is probably the configuration
, then
python manage.py runserver but it doesn't work (it's probably a setting problem)
and then
python manage.py runserver 0.0.0.0:8000
can be accessed

The web app can be anywhere in the python path.
Here we create it in the same directory as manage.py
Create
$ python manage.py startapp polls
Edit views.py 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 them to URLs


Create urls.py in the same directory to
edit

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

Then point to polls.urls in the global url

mysite/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

Pay attention to the ^ symbol, because the include function does not eat the $
. Use include to put URLs in various places. It is not necessary to put them together
. It is worth mentioning that the only exception is
admin.site.urls

We use the url function to establish the connection and
map view.py to the URL to the
url function:
parameter:
regex string
The string used for matching

If the view
matches the regex, it will call the specified view function
with httpRequest as the first parameter, and the matched characters as other parameters.
If the regex uses simple captures, values ​​are passed as positional arguments; if it uses named captures, values ​​are passed as keyword arguments. We'll give an example of this in a bit. I
don't understand, but there will be examples later

argument:kwargs
is in the dictionary, not introduced in the tutorial

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

part2 link database

Configure the database
I have installed mysql before and
now
install mysqlclient and report an error OSError: mysql_config not found
because it is not installed: libmysqlclient-dev
sudo apt-get install libmysqlclient-dev
Find the path of the mysql_config file
sudo updatedb
locate mysql_config
The location of mysql_config is: / usr/bin/mysql_config is not installed according to the source package
of http: //blog.163.com/zhu329599788@126/blog/static/6669335020161260025544/
It is just installed directly by Pip

The configuration file setting.py
is mainly the part of the Database to add some parameters

I changed the port of mysql again, from the default 3306 to 6666,
mainly because of the two port settings in /etc/mysql/my/cnf

Then run service mysql start again

When running the server, first
python manage.py migrate

Then added "polls" in installed_app in setting.py
python manage.py migration is actually the process of taking the configuration in setting.py into effect

Then modify the models.py under polls is probably the meaning of the database model
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 django.db A subclass of .models.Model is
called model

The variables under each model (Field subclasses under models) correspond to an item in the database.
You'll use this value in your Python code, and your database will use it as the column name.
Each model corresponds to an item in the database.
But in order for them to take effect, you must first
python manage.py makemigrations and
then
python manage.py migrate
. Each Field type variable can specify a name, and
some require parameters. For example, CharField requires a maxlength. This parameter will also be used for Field
in validation.
There can also be default values

We use ForeignKey to define a relationship.
Each Choice is linked to a Question.
Django supports a variety of database links.
Many-to-many, one-to-one, and many-to-one
In Django, the app is independent, and each app can Used by multiple projetcs

In Django in INSTALLED_APPS, it is best not to write "polls" directly,
you can write
"polls.apps.PollsConfig",
so the configuration file of polls is transferred to polls, which is very convenient
. There is a PollsConig class in apps.py
with a name The method returns the polls
action and the appeal thing should be the same as
python manage.py makemigrations polls

By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made new ones) and that you’d like the changes to be stored as a migration.

makemigrations just makes changes

This file is generated in
polls/migrations/0001_initial.py.
This file can be edited manually

Migrations are 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/0001_initial.py. Don’t worry, you’re not expected to read them every time Django makes one, but they’re designed to be human-editable in case you want to manually tweak how Django changes things.

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

python manage.py sqlmigrate polls 0001
This command can display the details of migrate and
convert it into sql language to operate the database

The result of the conversion depends on the specific database used (I guess engine does this)

The name of the table is a mixture of the app's name and the model's name

primary keys (id ) are added automatically (can be modified manually)

Conventionally, django adds _id corresponding to the Forenognkey file name (can be rewritten)

database-specific filed 取决于你的数据库
It’s tailored to the database you’re using, so database-specific field types such as auto_increment (MySQL), serial (PostgreSQL), or integer primary key autoincrement (SQLite) are handled for you automatically. Same goes for the quoting of field names – e.g., using double quotes or single quotes.

The sqlmigrate doesn't really do migrate, just output the sql statement to give you an idea

The command python manage.py check
is to check whether there is any problem in the project (do not actually do migrate or database)

summary

Three steps to change your database file
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.
It is designed this way to Make multi-person development easy
Read the django-admin documentation for full information on what the manage.py utility can do.

play with the api

python manage.py

Not a simple call to python,
because manage.py sets the
DJANGO_SETTINGS_MODULE environment variable.
You can get the path to the sfsite/setings.py file

If you don't want to do this, you can
just design the environment variable
DJANGO_SETTINGS_MODULE environment variable to mysite.settings

must be at the same level as manage.py
for import sfsite to be valid

After entering the shell, you can operate
...
import django
django.setup()
q = Question(question_text="What's new?", pub_date=timezone.now())

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

q.save()

Now it has an ID. Note that this might say "1L" instead of "1", depending

on which database you're using. That's no biggie; it just means your

database backend prefers to return integers as Python long integer

objects.

q.id
1

Access model field values via Python attributes.

q.question_text
"What's new?"
q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=

Change values by changing the attributes, then calling save().

q.question_text = "What's up?"
q.save()

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

Question.objects.all()
<QuerySet [

Re-punch the shell
to operate the database using the api provided by django

Question.objects.all() View all
Question.objects.filter(id=1) Filter
Question.objects.filter(question_text__startswith='What')
Note this notation, the method is represented by __ two underscores

>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

# Request an ID that doesn't exist, this will 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 is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.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 choices 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 have API access to their related Question objects.
>>> c.question
<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 you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the '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 allows you to operate on the database, which is
essentially a mapping of the classes in models.py

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325251559&siteId=291194637