current position:Home>Django ORM details - fields, attributes, operations
Django ORM details - fields, attributes, operations
2022-01-30 22:46:56 【Xiao Wang is not serious】
This is my participation 11 The fourth of the yuegengwen challenge 2 God , Check out the activity details :2021 One last more challenge
Django-ORM Detailed explanation - Field 、 attribute 、 operation
Common field types
CharField: Character type , You must provide max_length Parameters ,max_length Represents character length .
Email Field: Mailbox type , It's actually a character type , It only provides email format verification .
Text Field: Text type , Store large text strings . If the string exceeds 254 Characters. It is recommended to use Text Field.
Integer Field: Integer types .
Date Field: Date fields .
Time Field: The time field .
Date Time Field: datetime field , Combined date field and time field .
File Field: It's actually a string type , Used to save the path of the uploaded file in the database .
Image Field: It's actually a string type , Used to save the path of uploaded pictures in the database .
name=models.Char Field(max_length=32,verbose_name=' full name ')
verbose_name stay Django Admin The management background is the display name of the field , It can be understood as field alias ,verbose_name stay SQL There is no concrete embodiment of the level , That is to say, add or not verbose_name It has no effect on the fields in the database
email=models.Email Field(verbose_name=' mailbox ')
descript=models.Text Field(verbose_name=" brief introduction ")
int= models.Integer Field()
date=models.Date Field(auto_now=True, auto_now_add=False)
auto_now Parameter automatically saves the current time , It is generally used to indicate the last modification time . When you first create a record , Django take auto_now_add The field value is automatically set to the current time , Used to indicate the creation time of the record object .
time= models.Time Field(auto_now=False,auto_now_add=False)
datetime=models.Date Time Field(auto_now=False,auto_now_add=False)
filetest =models.Fiel Field (upload_to = 'test/')
picture = models.Image Field(upload_to = 'pic/')
Copy code
Common field properties
db_index:db_index=True Indicates that this field is set as the index of the database table .
title = models.Char Field(max_length=32, db_index=True)
unique:unique=True Indicates that the field cannot have duplicate values in the database table .
default: Set the default value of the field , Such as default='good'.
auto_now_add:Datetime Field、Date Field、Time Field this 3 Unique properties of fields , auto_now_add=True Indicates that the time when the new record is created is saved as the value of this field .
auto_now:Datetime Field、Date Field、Time Field this 3 Unique properties of fields ,auto_now= True Indicates each time a record is modified , Store the current time in this field .
ORM Basic data operation
Increase record
Mode one :
new_emp= models.employee.objects.create(name="tom",email="[email protected]",dep_id=66)
Copy code
Mode two :
new_emp= models.employee (name="tom",email="[email protected]",dep_id=66)
new_emp.save()
Copy code
Delete record
use filter() Filter out the qualified records and call them. delete() Delete
models. employee.objects.filter(name= " Zhang San ").delete()
Copy code
Modify the record
Updates the record of the specified condition , And updates the value of the specified field
models.employee.objects.filter(name='tom').update(email="[email protected]")
Copy code
Modify a single piece of data
obj = models.employee.objects.get(id=66)
obj.email = "[email protected]"
obj.save()
Copy code
Inquire about
Access to all
Emp_list= models.employee.objects.all()
Copy code
Get a single piece of data , If the data does not exist, an error is reported
Emp=models.employee.objects.get(id=123)
Copy code
Gets the recordset for the specified condition
Emp_group=models. employee.objects.filter(name= " Zhang San ")
Copy code
Django ORM Common functions for data operation
all() function , Return all qualified records .
objects = models.employee.objects.all()
Copy code
filter() function , Returns the record of the specified condition .filter The following parentheses are filter conditions , Be similar to SQL Middle sentence where The following conditional statement .
objects = models.employee.objects.filter(name='tom')
Copy code
# obtain name Field contains “Tom” The record of
models. employee.objects.filter(name__contains="Tom")
# obtain name Field contains “tom” The record of ,icontains Ignore case models.employee.objects.filter(name__icontains="tom")
# obtain employee In the data table id be equal to 10、20、66 The data of
models. employee.objects.filter(id__in=[10, 20, 66])
# obtain employee In the data table id It's not equal to 10、20、66 The record of , Because the front uses exclude
models. employee.objects.exclude(id__in=[10, 20, 66]).
# obtain employee In the data table id Greater than 1 And Less than 10 The record of , The relationship between the two filter conditions is equivalent to SQL Of and
models. employee.objects.filter(id__gt=1, id__lt=10)
# obtain employee In the data table id In scope 1~66 The records in , Equivalent to SQL Of id bettwen 1and 66
models. employee.objects.filter(id__range=[1, 66])
# obtain employee In the data table birthday The month in the field is 9 Monthly records ,birthday For date format
models. employee.objects.filter(birthday__month=9)
Copy code
order_by() function , according to order_by Sort the fields in parentheses .
objects =models.employee.objects.exclude(name='tom').order_by('name','id')
# Add in field name “-”, Indicates that the field is arranged in reverse order . The following code represents , Press name Arrange the list in reverse order of fields .
objects = models.employee.objects.order_by('-name')
Copy code
distinct() function , Remove identical records from the record set ( Repeat the record ), Then return the recordset .
objects = models.employee.objects.filter (name='tom').distinct()
Copy code
Other functions
values() function , Returns a dictionary type sequence .
objects = models.employee.objects.values('id','name','email')
Copy code
values_list() function , Returns a sequence of tuple types .
objects = models.employee.objects.values_list('id','name','email')
Copy code
get()、first()、last() Return a single object , It can be understood as returning a record in the data table .
# return id by 1 The record of , In parentheses are filter conditions
object1 = models.employee.objects.get(id=1)
# Returns the first record of the dataset
object2 = models.employee.objects.first()
# Returns the last record in the dataset
object3 = models.employee.objects.last()
# Returns the number of data sets
bject4= models.employee.objects.count()
Copy code
copyright notice
author[Xiao Wang is not serious],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201302246553437.html
The sidebar is recommended
- Introduction to python (IV) dynamic web page analysis and capture
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
guess what you like
-
This is what you should do to quickly create a list in Python
-
On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
-
Python OpenCV image area contour mark, which can be used to frame various small notes
-
How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
-
Initial Python tuple
-
Introduction to Python urllib module
-
Advanced Python Basics: from functions to advanced magic methods
-
Python Foundation: data structure summary
-
Python Basics: from variables to exception handling
-
Python notes (22): time module and calendar module
Random recommended
- Python notes (20): built in high-order functions
- Python notes (17): closure
- Python notes (18): decorator
- Python notes (16): generators and iterators
- Python notes (XV): List derivation
- Python tells you what timing attacks are
- Python -- file and exception
- [Python from introduction to mastery] (IV) what are the built-in data types of Python? Figure out
- Python code to scan code to pay attention to official account login
- [algorithm learning] 1221 Split balanced string (Java / C / C + + / Python / go / trust)
- Python notes (22): errors and exceptions
- Python has been hidden for ten years, and once image recognition is heard all over the world
- Python notes (21): random number module
- Python notes (19): anonymous functions
- Use Python and OpenCV to calculate and draw two-dimensional histogram
- Python, Hough circle transformation in opencv
- A library for reading and writing markdown in Python: mdutils
- Datetime of Python time operation (Part I)
- The most useful decorator in the python standard library
- Python iterators and generators
- [Python from introduction to mastery] (V) Python's built-in data types - sequences and strings. They have no girlfriend, not a nanny, and can only be used as dry goods
- Does Python have a, = operator?
- Go through the string common sense in Python
- Fanwai 4 Handling of mouse events and solutions to common problems in Python opencv
- Summary of common functions for processing strings in Python
- When writing Python scripts, be sure to add this
- Python web crawler - Fundamentals (1)
- Pandas handles duplicate values
- Python notes (23): regular module
- Python crawlers are slow? Concurrent programming to understand it
- Parameter passing of Python function
- Stroke tuple in Python
- Talk about ordinary functions and higher-order functions in Python
- [Python data acquisition] page image crawling and saving
- [Python data collection] selenium automated test framework
- Talk about function passing and other supplements in Python
- Python programming simulation poker game
- leetcode 160. Intersection of Two Linked Lists (python)
- Python crawler actual combat, requests module, python to grab the beautiful wallpaper of a station
- Fanwai 5 Detailed description of slider in Python opencv and solutions to common problems