current position:Home>Django model class 1
Django model class 1
2022-01-31 05:33:08 【laufing】
ORM
Class mapping to table
Class attributes are mapped to table fields
The object instance of the class is mapped to a row of records
== advantage ==
- Avoid writing SQL sentence , Use an object-oriented way to operate the database , Easy to use .
- Decouple the project from the database , Switching databases requires simple configuration .
== shortcoming ==
- For complex business , The operation is complicated
- No performance SQL Efficient
Django Configuration database
In profile settings.py in
DATABASES = {
"default":{
"ENGINE":"django.db.backends.mysql",
"HOST":"localhost",
"PORT":"3306",
"USER":"lauf",
"PASSWORD":"lauf123",
"NAME":"my_db",
"CHARSET":"utf8",
}
}
Copy code
== Be careful ==
django Connect mysql Use python Of mysqlclient library , Need to install :sudo pip3 install mysqlclient If an error mysql_config, You have in linux The following dependencies are installed in the system environment :
sudo apt-get install libmysqlclient-dev
sudo apt-get install default-libmysqlclient-dev
sudo apt-get install python3-dev
# Check whether the installation is successful
sudo apt list --installed | grep -E "libmysqlclient-dev|python3-dev"
Copy code
see pip3 Is the installation successful (mysqlclient)
pip3 freeze | grep -i "mysqlclient"
Copy code
Create model classes
Here it is user Application , Show how to create a model class
# Under the project directory , establish user application
python3 manage.py startapp user
# Install application settings.py
INSTALLED_APPS = [
...,
"user",
]
# Define model classes for applications user>models.py
from django.db import models
class User(models.Model):
username = models.CharField(" full name ",max_length=50,primary_key=True)# Must give max_length
password = models.CharField(" password ",max_length=50,null=False)
score = models.DecimalField(" fraction ",max_digits=4,decimal_places=2) # Decimal place
is_delete = models.BooleanField(" Whether or not to delete ",default=False)
created_time = models.DateTimeField(" Registration time ",auto_now_add=True)
updated_time = models.DateTimeField(" Update time ",auto_now=True)
def __str__(self):
""" When printing objects , Information displayed """
return self.username
class Meta:
db_table = "user_table" # Change table name
# Migrate model classes , To database
python3 manage.py makemigrations
python3 manage.py migrate
Copy code
When no primary key is specified ,Django Automatically create a id A primary key .
== Practice for user Table add a hobby Field ==
# In the model class , Add class attribute
hobby = models.CharField(" hobby ",max_length=50,default="") # Prevent previous data from reporting errors without this field , We must give one default
# Migrate to database
Copy code
Field type of model class
- BooleanField()
Corresponding to tinyint,0/1; Django In Chinese, it means True/False
- CharField()
Corresponding to varchar, Must specify max_length
- DateField()
Corresponding to date, Parameters ,auto_now = True, Update time auto_now_add = True, First insertion time default Give a default value
- DateTimeField() Use the same as DateField()
- FloatField() Corresponding to double
- DecimalField() Exact decimal , Corresponding database decimal Required parameters :max_digits=5 The total number of digits ,decimal_places=2 Decimal place
- EmailField() Corresponding database varchar
- IntegerField() -->int
- ImageField() --->varchar(100) Storage path
- TextField --->longtext Long text
Constraints on class properties
primary_key, bool, Whether the class attribute is a primary key
blank,bool, Is it empty ,admin Fields that can not be written during background management
null,bool, Whether the column can be null Null value
default, The default value is
db_index,bool, Whether to set index in this column
unique,bool, Whether the value of this column is unique , unique index
db_column Column name , By default, the class attribute is used as the column name
verbose_name, Field name displayed in the background
practice
Create a Book Model class , Class properties are as follows :
title, Title , Character type , Maximum length 50, And the value is unique
price, Price , Exact decimal , Maximum 5 digit , One decimal place
publish, Press. , Character type , Maximum length 50, Not for null
When printing objects , Output the title of the book , And modify the table name to book_table\
Be careful : Every time you modify the model class , All have to migrate ; Migration failed , Delete migrations Migration files in the directory , except __init.__py, Delete Library , Rebuild Library , Re migrate
copyright notice
author[laufing],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310533059366.html
The sidebar is recommended
- My friend's stock suffered a terrible loss. When I was angry, I crawled the latest data of securities with Python
- Python interface automation testing framework -- if you want to do well, you must first sharpen its tools
- Python multi thread crawling weather website pictures and saving
- How to convert pandas data to excel file
- Python series tutorials 122
- Python Complete Guide - printing data using pyspark
- Python Complete Guide -- tuple conversion array
- Stroke the list in python (top)
- Analysis of Python requests module
- Comments and variables in Python
guess what you like
-
New statement match, the new version of Python is finally going to introduce switch case?
-
Fanwai 6 Different operations for image details in Python opencv
-
Python crawler native code learning (I)
-
Python quantitative data warehouse building series 2: Python operation database
-
Python code reading (Part 50): taking elements from list intervals
-
Pyechart + pandas made word cloud pictures of 19 report documents
-
[Python crawler] multithreaded daemon & join() blocking
-
Python crawls cat pictures in batches to realize thousand image imaging
-
Van * Python | simple crawling of a planet
-
Input and output of Python practice
Random recommended
- Django ORM details - fields, attributes, operations
- Python web crawler - crawling cloud music review (3)
- Stroke list in python (bottom)
- What cat is the most popular? Python crawls the whole network of cat pictures. Which one is your favorite
- [algorithm learning] LCP 06 Take coins (Java / C / C + + / Python / go / trust)
- Python shows the progress of downloading files from requests
- Solve the problem that Django celery beat prompts that the database is incorrectly configured and does not support multiple databases
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python quantitative data warehouse construction 3: data drop library code encapsulation
- The source code and implementation of Django CSRF Middleware
- Python hashlib module
- The cover of Python 3 web crawler development (Second Edition) has been determined!
- The introduction method of executing Python source code or Python source code file (novice, please enter the old bird and turn left)
- [Python basics] explain Python basic functions in detail, including teaching and learning
- Python web crawler - crawling cloud music review (4)
- The first step of scientific research: create Python virtual environment on Linux server
- Writing nmap scanning tool in Python -- multithreaded version
- leetcode 2057. Smallest Index With Equal Value(python)
- Bamboolib: this will be one of the most useful Python libraries you've ever seen
- Python crawler actual combat, requests module, python realizes capturing a video barrage
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes | 538 | 1038 (Java / C / C + + / Python / go / trust)
- How IOS developers learn python programming 3-operator 2
- How IOS developers learn python programming 2-operator 1
- [Python applet] 8 lines of code to realize file de duplication
- Python uses the pynvml tool to obtain the working status of GPU
- Data mining: Python actual combat multi factor analysis
- Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
- Use Python VTK to batch read 2D slices and display 3D models
- Complete image cutting using Python version VTK
- Python interface automation test framework (basic) -- common data types Dict
- Python specific text extraction in actual combat challenges the first step of efficient office