Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Python Foundation (Django III-Model)

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article is followed by the previous Python Foundation (Django II).

7. Model

1. Description:

Model is born by Django to facilitate the program to operate the database, using the ORM mode.

Object-relational mapping (Object Relational Mapping, referred to as ORM) schema is a technology to solve the mismatch between object-oriented and relational databases. To put it simply, ORM automatically persists the objects in the program to the relational database by using the mapping relationship between the object and the database.

2. Use:

2-1. Create a Model (edit the models.py under the application directory)

From django.db import modelsclass Author (models.Model): # defines a class (table), which is the table name # defines a field (column) called first_name, the field type is string type, and the parameter setting maximum length is 32 bytes first_name = models.CharField (max_length=32) last_name = models.CharField (max_length=32) email = models.EmailField (null=True,blank=True) # the field type is mailbox There will be format validation def _ _ unicode__ (self): # the value displayed when defining the query class's data return's% s%% (self.first_name,self.last_name)

Field type:

1. Models.AutoField auto-increment column = int (11)

If not, a column named id will be generated by default, and if you want to display a custom self-incrementing column, you must set the given column to the primary key primary_key=True.

2. Models.CharField string field

Max_length parameter is required

3. Models.BooleanField Boolean type = tinyint (1)

Cannot be empty

4. Models.ComaSeparatedIntegerField numbers separated by commas = varchar

Inherit CharField, so you must have a max_lenght parameter

5. Models.DateField date type date

For the parameter auto_now = True, this time is updated with each update; auto_now_add is only created and added for the first time, and subsequent updates are no longer changed.

6. Models.DateTimeField date type datetime

The same parameters as DateField

7. Models.Decimal decimal type = decimal

You must specify integer max_digits and decimal decimal_places

8. Models.EmailField string type (regular expression mailbox) = varchar

Perform regular expressions on strings

9. Models.FloatField floating point type = double

10. Models.IntegerField × ×

11. Models.BigIntegerField length × × ×

Integer_field_ranges = {

'SmallIntegerField': (- 32768, 32767)

'IntegerField': (- 2147483648, 2147483647)

'BigIntegerField': (- 9223372036854775808,9223372036854775807)

'PositiveSmallIntegerField': (0, 32767)

'PositiveIntegerField': (0, 2147483647)

}

12. Models.IPAddressField string type (ip4 regular expression)

13. Models.GenericIPAddressField string type (ip4 and ip6 are optional)

Parameter protocol can be: both, ipv4, ipv6

When verifying, an error will be reported according to the setting

14. Models.NullBooleanField allows empty Boolean types

15. Models.PositiveIntegerFiel is positive Integer

16. Models.PositiveSmallIntegerField is positive smallInteger

17. Models.SlugField minus sign, underscore, letter, number

18. Models.SmallIntegerField digits

The fields in the database are: tinyint, smallint, int, bigint

19. Models.TextField string = longtext

20. Models.TimeField time HH:MM [: ss [.uuuuuuu]]

21. Models.URLField string, address regular expression

22, models.BinaryField binary

23. Models.ImageField pictures

24. Models.FilePathField file

Parameters:

1 、 null=True

Whether the field in the database can be empty

2 、 blank=True

Whether null values are allowed when data is added to the Admin of django

3. Primary_key = False

Primary key, after setting the primary key on AutoField, it will replace the original self-increasing id column.

4. Auto_now and auto_now_add

Auto_now is automatically created-whether added or modified, is the time of the current operation

Auto_now_add is created automatically-always the time when it is created

5 、 choices

GENDER_CHOICE = (

(upright Mouse, ubiquitous Male')

(upright Fleming, upright Female')

)

Gender = models.CharField (max_length=2,choices = GENDER_CHOICE)

6 、 max_length

7. Default default value

8. The display name of the field in verbose_name Admin

9. Name | Field name in db_column database

10. Unique=True does not allow repetition

11. Db_index = True database index

12. Whether editable=True is editable in Admin

13. Error_messages=None error prompt

14. Auto_created=False is created automatically

15. Help_text prompts for help information in Admin

16 、 validators= []

17 、 upload-to

# related commands

Python manage.py validate # is used to check the correctness of models.py syntax

Python manage.py makemigrations

Python manage.py migrate # automatically creates database tables based on the classes defined in the code

2-2. Manipulate database tables

From app01 import models# add # # first: models.Author.objects.create (first_name='zhang',last_name='san',email='z@test.com') # second: data of dictionary type dic = {'first_name':' li', 'last_name':' si' 'email':' zroomtest.com} models.Author.objects.create (* * dic) # third: obj = models.Author (* * dic) obj.save () # check # models.Author.objects.all () # get all the data in the Author table # filter query filter () method gets a list The get () method gets a single object models.Author.objects.get (first_name='zhang') # Author is the table name and first_name is the field name Zhang is the keyword models.Author.objects.filter (last_name='san') models.Author.objects.filter (first_name='zhang') of the query Last_name='san') # query conditions can have multiple models.Author.objects.exclude (first_name='zhang') # query first_name is not equal to zhang's models.Author.objects.filter (first_name='zhang'). Count () # get the number of data that meets the query conditions # multiple query models.Author.objects.filter (first_name='zhang'). Order_by ("email") # restrict query models.Author.objects. Order_by ('first_name') [0] # take the first value of the query result QuerySet # sort models.Author.objects.order_by ("first_name") # sort the results models.Author.objects.order_by ("first_name") according to a field value "last_name") # sort by multiple fields, and the second field will be used in models.Author.objects.order_by ("- first_name") # reverse sorting if the first field has the same value, with a minus sign-prefix # that connects the query field with the corresponding operation using a double underscore (excerpt from other blogs) # greater than Less than models.Tb1.objects.filter (id__gt=1) # get values with id greater than 1 models.Tb1.objects.filter (id__lt=10) # get values with id less than 10 models.Tb1.objects.filter (id__lt=10, id__gt=1) # get values with id greater than 1 and less than 10 # inmodels.Tb1.objects.filter (id__in= [11,22) 33]) # get data with id equal to 11,22,33 models.Tb1.objects.exclude (id__in= [11,22,33]) # not in# containsmodels.Tb1.objects.filter (name__contains= "ven") # for fuzzy matching name fields. Models.Tb1.objects.filter (name__icontains= "ven") # icontains case insensitive models.Tb1.objects.exclude (name__icontains= "ven") # inverted # rangemodels.Tb1.objects.filter (id__range= [1) 2]) # range bettwen and# change # # add a modification operation to the query # first: models.Author.objects.filter (last_name='si') .update (last_name='SI') # second: data of dictionary type dic = {'first_name':' li', 'last_name':' si' Models.Author.objects.filter (last_name='si'). Update (* * dic) # third: obj = models.Author.objects.get (last_name='si') obj.email = 'new@test.com'obj.save () # delete # # add a delete operation models.Author.objects.filter (last_name='san'). Delete () to the query

2-3. Connected table structure

Description:

Django's ORM has a variety of relationships:

One on one: one belongs to only one.

One to many: one belongs to more than one

Many to many: one has many and belongs to many

They are defined in the following ways:

One-to-one: models.OneToOneField (other tables)

One to many: models.ForeignKey (other tables)

Many to many: models.ManyToManyField (other tables)

Application scenarios:

One-to-many: when a row of data is created in a table, there is a single drop-down box (which can be repeatedly selected)

For example, when creating user information, you need to select a user type [ordinary user] [Gold user] [Platinum user] and so on.

Many-to-many: to create a row of data in a table, there is a drop-down box that can be selected multiple

For example, to create user information, you need to specify multiple hobbies for the user

One-to-one: when you create a row of data in a table, there is a single drop-down box (the contents of the drop-down box disappear after being used once

For example:

# models.py

#-*-coding:utf-8-*-from _ future__ import unicode_literalsfrom django.db import models# Create your models here.# OneToMany example 1class UserType (models.Model): caption = models.CharField (max_length=32) def _ unicode__ (self): return self.captionclass UserInfo (models.Model): user_type = models.ForeignKey (UserType) username = models.CharField (max_length=32) age = models.IntegerField () def _ _ unicode__ (self): return self.username# OneToMany example 2class MyUser (models.Model): username = models.CharField (max_length=16) password = models.CharField (max_length=16) def _ unicode__ (self): return self.usernameclass News (models.Model): title = models.CharField (max_length=32) content = models.CharField (max_length=32) def _ unicode__ (self): return Self.titleclass Favor (models.Model): user_obj = models.ForeignKey (MyUser) new_obj = models.ForeignKey (News) def _ _ unicode__ (self): return "% s-- >% s"% (self.user_obj.username Self.new_obj.title) # ManyToMany example 1class Host (models.Model): hostname = models.CharField (max_length=32) port = models.IntegerField () def _ unicode__ (self): return self.hostnameclass HostAdmin (models.Model): username = models.CharField (max_length=32) email = models.CharField (max_length=32) host = models.ManyToManyField (Host) def _ unicode__ (self): return self. Username# ManyToMany example 2 create many-to-many relational tables manually No need for Django automatic creation The advantage is that the fields of the third table can be customized''class Host2 (models.Model): hostname = models.CharField (max_length=32) port = models.IntegerField () def _ unicode__ (self): return self.hostnameclass HostAdmin2 (models.Model): username = models.CharField (max_length=32) email = models.CharField (max_length=32) host = models.ManyToManyField (Host2) Through= "HostRelation") def _ _ unicode__ (self): return self.usernameclass HostRelation (models.Model): host_obj = models.ForeignKey (Host2) admin_obj = models.ForeignKey (HostAdmin2)

# views.py

User_type_id=1) # user_type_id is a field name automatically generated by Django in an one-to-many relational table # second: the field in which ForeignKey is assigned uses an object user_type_obj = models.UserType.objects.get (id=2) # first get an object models.UserInfo.objects.create (username='test2',age=14) from the user_type table User_type=user_type_obj) # assign using the object you just got (note the field name) # forward lookup # (that is, query data from the table of the field where ForeignKey is located) # single table query models.UserInfo.objects.filter (username='test1') # query data in the UserInfo table where the value of the username field is' test1' # Cross-table query Query the field of ForeignKey + double underscore + the field in the spanned table (the field of ForeignKey is an object) # models.UserInfo.objects.filter (user_type__caption='CEO') # query the value of the caption field of the user_type object in the UserInfo table is CEO data ret = models.UserInfo.objects.filter (user_type__id=2) # syntax same as above (point) print i.username I.user_type.caption # reverse lookup # (that is, query data from the table associated with the ForeignKey field) # single table query line = models.UserType.objects.get (id=1) # get an id=1 object from the UserType table # Cross-table query # first: query models.UserType.objects.get by the lowercase table name of the spanned table + double underscore + the field to be queried (userinfo _ _ username='test1') # userinfo is an object that django automatically creates in the UserType table That is, the value of all the user_type=1 in the UserInfo table # the goal of this query is to reverse query all the data of user_type=1 and username=test1 in the UserInfo table through the UserType table, line.userinfo_set.all (). Count () # calculate the number of data that meet the query conditions # multi-level query Models is "OneToMany example 2" ret = models.News.objects.filter (favor__user_obj__username='zhangsan') # query table order is News-> Favor-> MyUser # first reverse cross-table query: query user_obj objects in Favor table through News table # and then forward cross-table query: query users with zhangsan field value in Myuser table through user_obj object # the most Email='1@qq.com') # create a user The managed host is empty # adding # admin_obj = models.HostAdmin.objects.get (username='a1') # first get a user object host_list = models.Host.objects.filter (id__lt=3) # and then get multiple host objects admin_obj.host.add (* host_list) # add multiple manageable for a user Note that hostadmin_set # forward query # admin_obj = models.HostAdmin.objects.get (username='a1') # first get a user object host_list = admin_obj.host.all () # query all hosts managed by the user for i in host_list: print i.hostname I.port # reverse query # host_obj = models.Host.objects.get (hostname='h2') # first get a host object admin_list = host_obj.hostadmin_set.all () # query all administrators of the host for i in admin_list: print i.username I.email # Custom many-to-many relationship # # models adds data models.HostRelation.objects.create for "ManyToMany example 2" # (host_obj_id = 1, # equals host_obj = models.Host2.objects.get (id=1) admin_obj_id = 1 # hostname of the host managed by the user # Django F # # Operation on a column of values in the object from django.db.models import F models.Host.objects.filter (hostname='h2') .update (port=F ('port') + 1) # add 1 models.Host.objects.update (port=F (' port') + 1) to the port value of all hostname=h2 data in the Host table (port=F ('port') + 1) # add all port values in the Host table to 1 # Django ('h2') # children adds Yuanzu Query fields support using some built-in methods q1.children.append (('hostname','h3')) # to add multiple query conditions q1.children.append ((' hostname','h6')) ret_list = models.Host.objects.filter (Q1) # query using Q1 object (for Host table) for i in ret_list: print'% s->% s% (i.hostname) I.port) # Multi-Q multi-conditional query con = Q () # create an outer Q object Q can be nested Q2 = Q () q2.connector = 'OR' q2.children.append ((' port','23')) # query data with port field value equal to 23 q2.children.append (('port__gt','23')) # query data con.add with port field value greater than 23 (Q1SCHAND') # add Q1 to the previously defined outermost Q object The query condition is' and 'con.add (Q2jinghonand`) # to add Q2 to the outermost Q object defined earlier The query condition is' and 'ret_list = models.HostAdmin.objects.filter (con) # the result of the query is data that satisfies both Q1 and Q2 conditions (for HostAdmin table) for i in ret_list: print'% s->% swatch% (i.hostnamethei.port) # Multi-Q multi-conditional cross-table query q1.children.append (('username','a1')) q1.children.append ((' username') 'a2') q1.children.append (('username','a3')) q2.children.append ((' host__hostname','h5')) # supports cross-table queries Host is the field of table name + double underscore + query con.add (Q1gramme and') con.add (Q2 recording AND') ret_list = models.HostAdmin.objects.filter (con) # query user name is A1 or a2 or A3 and the management host name is h5 (for HostAdmin table) for i in ret_list: print i.username return HttpResponse ('ok') # has no special meaning, but the function requires a return value.

Some of the contents and ideas of the blog are sorted out from Wu Peiqi's blog.

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.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report