In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Django Model of Python full Stack Road Series
MTV development mode
The concept of combining data access logic, business logic, and presentation logic is sometimes referred to as the Model-View-Controller (MVC) pattern of software architecture. In this mode, Model represents the data access layer, View represents the part of the system that chooses what to display and how to display, and Controller refers to the part of the system that accesses the model based on user input and as needed to decide which view to use.
Django follows this MVC pattern closely and can be called a MVC framework.
The following are the meanings of M, V, and C in Django:
* * masks: data access part, which is handled by the django database layer
* * visual display: select which data to display and how to display it, which is handled by the view and template
* * delegated views: based on user input, the Django framework calls the appropriate Python function for a given URL according to the URLconf settings
C is handled by the framework itself, while Django focuses more on Model, Template, and Views. Django is also known as the MTV framework, in the MTV development pattern:
* * masks * stands for Model, or data access layer, which handles all transactions related to data: how to access, how to verify validity, what behaviors are included, and the relationships between data, etc.
* * templates * stands for Template, or presentation layer, which handles performance-related decisions: how to display them in pages or other types of documents
* * Vails * represents the View, or business logic layer, which contains the logic for accessing the model and fetching the appropriate template. You can think of it as a bridge between the model and the template.
Database configuration
The database of Django is configured in the settings.py file. Open this file and find the DATABASES field to configure the database:
DATABASES = {'default': {' ENGINE': 'django.db.backends.mysql',' NAME': 'mydatabase',' USER': 'root',' PASSWORD': 'as',' HOST': '127.0.0.1,' PORT': '3306,}}
The following are the configuration properties of an MySQL database:
Field describes the database engine NAME database name USER which user connects to the database PASSWORD user's password HOST database server PORT port
Built-in databases supported by the ENGINE field
Django.db.backends.postgresql
Django.db.backends.mysql
Django.db.backends.sqlite3
Django.db.backends.oracle
No matter which database you choose to use, you must install the driver of this database, that is, the media where python operates the database. What you need to note here is that python3.x does not support the use of MySQLdb module, but you can replace mysqldb through pymysql. First, you need to install pymysql module:
Pip3 install pymysql
Then add the following two lines of configuration to the project's _ _ init__.py file:
Import pymysqlpymysql.install_as_MySQLdb ()
When the database configuration is complete, we can enter the project test using python manage.py shell and enter the following instructions to test your database configuration:
E:\ DarkerProjects > python manage.py shellPython 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) > > from django.db import connection > cursor = connection.cursor ()
If no error message is displayed, then your database configuration is correct.
The first application
Let's create a Django app, a complete Django application that contains models, views, and Django code in the form of a separate Python package.
The difference between Project and app is that one is configuration and the other is code:
A Project contains many Django app and configurations for them
Technically, the role of Project is to provide configuration files, such as where to define database connection information, the list of installed app, TEMPLATE, etc.
An app is a collection of Django functions, usually including models and views, and exists as a package structure of Python
For example, Django itself has some built-in app, such as an annotation system and an automatic management interface, and one of the key points of app is that they can be easily ported to other Project and reused by multiple Project.
If you use Django's database layer (model), you must create a Django app, and the model must be stored in apps, so in order to start building our model, we must create a new app:
E:\ DarkerProjects > python manage.py startapp darker
E:\ DarkerProjects this is the root directory of my project. After the creation is completed, the following files are automatically created:
E:\ DarkerProjects > tree / f darker folder PATH list volume serial number is 0003-4145E:\ DARKERPROJECTS\ DARKER │ admin.py │ apps.py │ models.py │ tests.py │ views.py │ _ _ init__.py │└─ migrations _ _ init__.py first model
First, we need to create three tables, which are:
Student table (student), with fields: id/sname/gender
Course schedule (course), with fields: id/cname
Transcript (score), with fields: id/student_id/course_id
Open the models.py directory of app and enter the following code:
From django.db import models# Create your models here.class student (models.Model): # self-increment primary key id = models.AutoField sname = models.CharField (max_length=12) gender = models.CharField (max_length=2) class course (models.Model): # self-increment primary key id = models.AutoField cname = models.CharField (max_length=12) class score (models.Model): # self-increment primary key id = models.AutoField # set foreign key association student_id = models.ForeignKey (student) course_id = models.ForeignKey (course)
Each data model is a subclass of django.db.models.Model, and its parent class, Model, contains all the necessary methods to interact with the database, and provides a concise and beautiful syntax for defining database fields. Each model is equivalent to a single database table, and each attribute is a field in this table. The attribute name is the field name.
Model installation
To create these tables in the database through django, we first need to activate these models in the project and add darker app to the list of installed applications in the configuration file to complete this step
Edit the settings.py file, find the INSTALLED_APPS settings, and INSTALLED_APPS tells the Django project which app is active:
INSTALLED_APPS = ['django.contrib.admin',' django.contrib.auth', 'django.contrib.contenttypes',' django.contrib.sessions', 'django.contrib.messages',' django.contrib.staticfiles', 'darker',]
Create the datasheet with the following instructions:
# check whether it is correct E:\ DarkerProjects > python manage.py checkSystem check identified no issues (0 silenced). # generate tables in the database E:\ DarkerProjects > python manage.py makemigrationsMigrations for 'darker': darker\ migrations\ 0002_auto_20160809_1423.py:-Create model course-Create model score-Create model student-Remove field authors from book-Remove field student from book-Delete model Author-Delete model Book-Delete model student-Add field Student_id to score# generate data E:\ DarkerProjects > python manage.py migrateOperations to perform: Apply all migrations: admin Auth, contenttypes, darker, sessionsRunning migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying darker.0001_initial... OK Applying darker.0002_auto_20160809_1423... OK Applying sessions.0001_initial... OK
Previous versions of django1.7 are:
Python manage.py syncdb
Django1.7 and later versions have been modified to split 1 step into 2 steps and become:
Python manage.py makemigrationspython manage.py migrate
View the created datasheet:
Mysql > show tables +-- + | Tables_in_mydb | +-+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | darker_course | | darker_score | | darker_student | | django_admin_log | | django_content_type | | django_migrations | | django_session | +-+ 13 rows in set (0.00 sec) basic data access
Run python manage.py shell and use the advanced Python API provided by Django
E:\ DarkerProjects > python manage.py shell# imports the student model class, through which we can interact with the student data table > from darker.models import student# to create an instance of the student class and set the field sname, the value of gender > S1 = student (sname= "ansheng", gender= "male") # call the object's save () method Save the object to the database, Django will execute an INSERT statement in the background > s1.save () # insert a piece of data > S2 = student (sname= "as", gender= "female") > > s2.save () # use the student.objects attribute to fetch the recordset of the student table from the database. There are many ways to do this. The student.objects.all () method gets all the objects of the student class in the database. In fact, Django executes a SQL SELECT statement > student_list = student.objects.all () > student_list to display the obtained data in string format.
We can simply solve this problem by adding a method _ _ str__, to the above three table classes as follows:
From django.db import models# Create your models here.class student (models.Model): id = models.AutoField sname = models.CharField (max_length=12) gender = models.CharField (max_length=2) def _ str__ (self): return self.sname class course (models.Model): id = models.AutoField cname = models.CharField (max_length=12) def _ str__ (self): return self.cname Class score (models.Model): id = models.AutoField student_id = models.ForeignKey (student) course_id = models.ForeignKey (course)
Then ctrl+c launched shell and re-entered.
E:\ DarkerProjects > python manage.py shellPython 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) > > from darker.models import student > student_list = student.objects.all () > > student_list# gets the string instead of the object insert and update data this time
Insert data
S1 = student (sname= "Ansheng", gender= "male")
Save data to a database
> > s1.save ()
Get the record primary key id that has just been inserted
> s1.id3
Modify data content
> s1.gender = "female" > s1.save ()
It is equivalent to executing the following SQL instruction
UPDATE darker_student SET gender = 'female' WHERE id=3; Select object
The following instruction is to get all the data from the database:
> > student.objects.all ()
Instead of using SELECT*, when selecting all data, Django explicitly lists all fields, SELECT* will be slower, and most importantly, listing all fields follows a Python creed: words are better than hints.
Data filtering
Use the filter () method to filter data
> student.objects.filter (sname= "Ansheng", gender= "female")
There is a double underscore between sname and contains, and the gender part is translated into LIKE statements by Django:
> student.objects.filter (sname__contains= "a")
Translated into the following SQL
SELECT id, sname, gender FROM darker_student WHERE name LIKE'% a%'
Get a single object
> > student.objects.get (sname= "as")
Data sorting
Sort using the order_by () method
> student.objects.order_by ("sname")
If you need to sort by multiple fields (the second field will be used if the value of the first field is the same), you can use multiple parameters, as follows:
> student.objects.order_by ("sname", "gender")
We can also specify reverse sorting, preceded by a minus sign-prefix:
> student.objects.order_by ("- sname")
Set the default sort of data
If you set this option, the related return values of the student object will be sorted by sname field by default when you use Django's database API to retrieve it, unless you specifically use order_by () when you retrieve it.
Class student (models.Model): id = models.AutoField sname = models.CharField (max_length=12) gender = models.CharField (max_length=2) def _ _ str__ (self): return self.sname class Meta: ordering = ['sname']
Chain query
> student.objects.filter (id= "2"). Order_by ("- sname")
Limit the data returned
> student.objects.order_by ('sname') [0] > student.objects.order_by (' sname') [1]
Similarly, you can use Python's list slices to get the data:
> student.objects.order_by ('sname') [0:2]
Although negative indexes are not supported, we can use other methods, such as slightly modifying the order_by () statement to achieve:
> student.objects.order_by ('- sname') [0] updates multiple objects
To change a specified column, we can call the update () method of the result set (QuerySet) object:
> student.objects.filter (id=2) .update (sname='Hello') 1
The update () method works for any result set (QuerySet), which means you can update multiple records at the same time. Here's an example that changes all genders to women:
> student.objects.all () .update (gender=' female') 3
The update () method returns an integer value indicating the number of records affected
Delete object
To delete an object in the database, simply call the object's delete () method.
Delete specified data
> student.objects.all () .filter (sname= "ansheng") .delete (); (1, {'darker.student': 1,' darker.score': 0}) > student.objects.all ()
Delete all data
> student.objects.all () .delete () (3, {'darker.student': 3,' darker.score': 0}) > student.objects.all () Field attribute description models.AutoField self-incrementing column, which generates an id column by default. If you want to display a custom self-incrementing column, you must set the given column as the primary key primary_key=Truemodels.CharField string field. It must have the max_length parameter models.BooleanField Boolean type and cannot be empty. Blank=Truemodels.ComaSeparatedIntegerField numbers separated by commas must have the max_lenght parameter models.DateField date type. For the parameter, auto_now = True, this time is updated each time. Auto_now_add is only added for the first time, and subsequent updates no longer change the parameter models.Decimal decimal type of models.DateTimeField date type datetime and DateField. You must specify integer max_digits and decimal decimal_placesmodels.EmailField string type (regular expression mailbox) models.FloatField floating point type models.IntegerField × × models.BigIntegerField length × × models.IPAddressField string type (ip4 regular expression) models.GenericIPAddressField string type (ip4 and ip6 are optional) Parameter protocol can be: both, ipv4, ipv6. When verifying, the Boolean type models.PositiveIntegerFiel positive Integermodels.PositiveSmallIntegerField positive smallIntegermodels.SlugField minus sign, underscore, alphanumeric models.SmallIntegerField number is allowed to be empty according to the setting of models.NullBooleanField. The fields in the database are: tinyint, smallint, int, bigintmodels.TextField string models.TimeField time models.URLField string Address regular expression models.BinaryField binary models.ImageField Picture models.FilePathField File attribute method description
Whether the field in the null=True database can be empty
Whether null values are allowed when data is added to the Admin of blank=Truedjango
Primary_key = False primary key. After setting the primary key on AutoField, it will replace the original self-increasing id column.
Automatic creation of auto_now-whether added or modified, is the time of the current operation
Automatic creation of auto_now_add-always the time of creation
Max_length maximum
Default default value
Display name of the field in verbose_nameAdmin
Field names in the name vertical bar db_column database
Unique=True does not allow repetition
Db_index = True database index
Is editable=True editable in Admin?
Error_messages=None error prompt
Automatic creation of auto_created=False
Help_text prompts for help information in Admin
Connected table structure method describes models.ForeignKey (other tables) one-to-many models.ManyToManyField (other tables) many-to-many models.OneToOneField (other tables) one-to-one
# Python full Stack Road # Django
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.