Get the App
SLTechnology News&Howtos  ›  Database  › 

Model creation Table based on Django

Shulou Source: shulou.com Published: 2022-06-01 14:41:38 10月01日 Update

First, create a single table

Models.py

#! / usr/bin/env python#-*-coding:utf-8-*-from _ future__ import unicode_literalsfrom django.db import modelsclass UserInfo (models.Model): USER_TYPE_LIST = ((1, "F"), (2, "M"),) name = models.CharField (max_length=32,primary_key=True) user_type = models.IntegerField (choices=USER_TYPE_LIST) Default=1) ctime = models.DateTimeField (auto_now=True) uptime = models.DateTimeField (auto_now_add=True) email = models.EmailField (max_length=32,null=True) email_default = models.EmailField (max_length=32,default= "admin@163.com") ip = models.GenericIPAddressField (protocol='both',null=True,blank=True) img = models.ImageField (null=True,blank=True,upload_to= "upload") def _ unicode__ (self): return self.name

The effect of creating a database single table is as follows:

Create a user:

View the table data again:

Create one of the tables to many, using the foreign key models.ForeignKey ("xxx")

Models.py

Pepole (models.Model):

Name = models.CharField (=)

Country = models.CharField (=)

Property (models.Model):

Size = models.CharField (=)

Weight = models.CharField (=)

Length = models.CharField (=)

The two tables Pepole and Property are associated through the foreign key models.ForeignKey (Pepole)

By default, the association is generated through the id field of the pepole table, and the property table generates color_id to store the id of the pepole table, as shown below:

If we generate data in the pepole table, the following id appears:

At the same time, you can see in the property table that the optional numbers of the associated items are 1, 2, 3, 4.

When do you usually use foreign keys? For example, we want to create a business line as well as a host, but the host belongs to a certain business line, so we can use foreign keys to create one-to-many tables. The code is as follows:

Class Business (models.Model):

Name = models.CharField (max_length=16)

Class Host (models.Model):

Hostname = models.CharField (max_length=32)

Or

Class Business (models.Model):

Name = models.CharField (max_length=16)

Class Host (models.Model):

Hostname = models.CharField (max_length=32)

You can also bind through the specified field

Class Business (models.Model):

Nid = models.AutoField (primary_key=True)

Name = models.CharField (max_length=16,unique=True)

Class Host (models.Model):

Hostname = models.CharField (max_length=32)

Business = models.ForeignKey ('Business',to_field='nid')

Table Business

Table Host

Table Host associated fields

Third, create many-to-many tables using models.ManyToManyField ('xxxx')

UserGroup (models.Model):

Group_name = models.CharField (=)

User (models.Model):

Name = models.CharField (=)

Email= models.EmailField (=)

User_to_group = models.ManyToManyField ()

A user can belong to multiple user groups, and a user group can contain multiple users, establishing a many-to-many association.

UserGroup table:

User table

Relationship:

Create an associated table user_user_to_group through the user_id and usergroup_id of two tables

That is, through the code of two tables, the system automatically helps to create the third table (associated table user_user_to_group)

4. Common operation of database

# increase

one

# models.Tb1.objects.create adds a piece of data to accept dictionary type data * * kwargs

two

# obj = models.Tb1 (c1diagnostic xxx, c2roomoo')

# obj.save ()

three

Dic = {'c1mm / c1mm / c2mm / c2mm

Models.Tb1.objects.create (* * dic)

# check

#

# models.Tb1.objects.get (id=123) # get a single piece of data. If it doesn't exist, an error will be reported (not recommended)

# models.Tb1.objects.all () # get all

# models.Tb1.objects.all () .first () # take the first piece of data

# models.Tb1.objects.filter (name='seven') # get the data of the specified condition

# Delete

#

# models.Tb1.objects.filter (name='seven') .delete () # Delete the data under the specified condition

# change

one

# models.Tb1.objects.filter (name='seven') .update (gender='0') # updates the data of specified conditions, all of which support * * kwargs and dictionary type data

two

# obj = models.Tb1.objects.get (id=1)

# obj.c1 = '111'

# obj.save () # modify single data

Query example:

Models.py

SimpleModel (models.Model):

Username = models.CharField (=)

Password = models.CharField (=)

Query operation home.py

Def index (request): dic = {'usernamehorse models.SimpleModel.objects.create (* * dic) ret = models.SimpleModel.objects.all () # get all the data print ret # is a list of objects [], print type (ret) # outputs a QuerySet type of django Print ret.query # outputs a select query statement ret = models.SimpleModel.objects.all () .values ('username') # to get only one column data Here we get the username column print ret,type (ret) # each data type obtained here is a dictionary # [{'username':'u'alex''}] ret = models.SimpleModel.objects.all (). Values_list (' username') # where each data type is a tuple print ret,type (ret) # [(uplialex') )] obj = HomeForm.ImportForm () return render (request,'home/index.html', {'obj':obj})

Get data from file

#! / usr/bin/env python#-*-coding:utf-8-*-_ _ author__ = 'ryan'from django import formsclass ImportForm (forms.Form): HOST_TYPE_LIST = (1' physical machine'), (2 ) host_type = forms.IntegerField (widget=forms.Select (choices=HOST_TYPE_LIST)) hostname = forms.CharField (widget=forms.PasswordInput ()) import json dic = ((1, "abc"), (2, "abcd"), (3, "abcdef")) f = open ('db_admin' 'w') f.write (json.dumps (dic)) f.close () fr = open ("db_admin") data = fr.read () data_tuple = json.loads (data) # get data from a file Later, the query result of changing this part into a sql statement is to get data from the database admin = forms.IntegerField (widget=forms.Select (choices=data_tuple)) def _ _ init__ (self,*args,**kwargs): super (ImportForm,self). _ _ init__ (* args) * * kwargs) # executes the constructor of the parent class import json fr = open ("db_admin") data = fr.read () data_tuple = json.loads (data) self.fields ['admin']. Widget.choice = data_tuple

Get data from database

#! / usr/bin/env python#-*-coding:utf-8-*-_ _ author__ = 'ryan'from django import formsfrom app01 import modelsclass ImportForm (forms.Form): HOST_TYPE_LIST = ((1)' physical machine'), (2) host_type = forms.IntegerField (widget=forms.Select (choices=HOST_TYPE_LIST)) hostname = forms.CharField (widget=forms.PasswordInput ()) import json dic = ((1) "abc"), (2, "abcd"), (3, "abcdef")) f = open ('db_admin','w') f.write (json.dumps (dic)) f.close () fr = open ("db_admin") data = fr.read () data_tuple = json.loads (data) # get data from the file Later, the query result of changing this part into a sql statement is to get data from the database admin = forms.IntegerField (widget=forms.Select (choices=data_tuple)) def _ _ init__ (self,*args,**kwargs): super (ImportForm,self). _ init__ (* args,**kwargs) self.fields ['admin']. Widget.choice = models.SimpleModel.objects.all (). Values_list (' id','username')

V. Advanced operation of the database

# get the number

# models.Tb1.objects.filter (name='seven'). Count ()

# greater than, less than

# models.Tb1.objects.filter (id__gt=1) # get a value whose id is greater than 1

# models.Tb1.objects.filter (id__lt=10) # get a value whose id is less than 10

# models.Tb1.objects.filter (id__lt=10, id__gt=1) # get values with id greater than 1 and less than 10

# in

# models.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

# contains

# models.Tb1.objects.filter (name__contains= "ven")

# models.Tb1.objects.filter (name__icontains= "ven") # icontains is case insensitive

# models.Tb1.objects.exclude (name__icontains= "ven")

# range

# models.Tb1.objects.filter (id__range= [1,2]) # range bettwen and

# other similar

# startswith,istartswith, endswith, iendswith

# order by

# models.Tb1.objects.filter (name='seven'). Order_by ('id') # asc

# models.Tb1.objects.filter (name='seven'). Order_by ('- id') # desc

# limit 、 offset

# models.Tb1.objects.all () [10:20]

# group by

From django.db.models import Count, Min, Max, Sum

# models.Tb1.objects.filter (C1: 1) .values ('id') .annotate (c=Count (' num'))

# SELECT "app01_tb1". "id", COUNT ("app01_tb1". "num") AS "c" FROM "app01_tb1" WHERE "app01_tb1". "C1" = 1 GROUP BY "app01_tb1". "id"

Tags: Data association database user type query dictionary field condition result statement utf-8 business host code content simultaneous multiple file time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Xiaomi Huawei Shulou Technology Shulou Tech Info