程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django data model

編輯:Python

Django The model is similar to java In language jpa equally , Reduce data for creating data , Simplify operations in the developing database .

from django.db import models
from django.urls import reverse
# Create your models here.
class UserBaseInfo(models.Model):
id = models.AutoField(verbose_name=' Number ', primary_key=True)
username = models.CharField(verbose_name=' User name ', max_length=30)
password = models.CharField(verbose_name=' password ', max_length=20)
status = models.CharField(verbose_name=' state ', max_length=1)
createdate = models.DateTimeField(
verbose_name=' Date of creation ', db_column='createDate')
def __str__(self):
return str(self.id)
class Meta:
verbose_name = ' Basic information of personnel '
db_table = 'UserBaseInfo4'

Field type

Field explain Corresponding mysql Field AutoField Self increasing primary key IntBooleanField Boolean fields TinyintCharField Character type varCharDateField date DateDateTimeField Date time type DateTimeIntergetField Integer types IntTexField Long text LongtextTimeField Time TimeFloatField Floating point numbers DoubleFileField Character type varCharImageField Character type varCharDecimalField value type Decimal

Attribute comments :
DecimalField:

  • max_digits: Maximum number
  • decimal_places: The maximum number of decimal places
    Field time types are auto_now_add and auto_now

Field parameters

Field explain verbose_name Display name of the field primary_key Set whether the field is a primary key editable Editable or not max_length Maximum length blank Whether it can be null , The default is falsenull Whether it can be null , The default is falsedefault The default value is choices Optional value db_column Column name db_index Whether to index unique Whether to establish uniqueness error_messages Custom error message validators Custom error validation

Str

Set the return value of the model

Meta class

Used for definition Django Model behavior

Field explain abstract Is it an abstract class db_table Table name managedDjango Manage the lifecycle and migration of tables ordering The returned data is sorted by that field verbose_name The name of the model displayed in the background index_together Joint index unique_together Joint constraint

Table relations

  • one-on-one
    OneToOneField

Parameters :
to The model name
to_field Associated field name
on_delete Deleted configuration

Field explain CASCADE cascading deletion PROTECT Error deleting SET_NULLnull = True It's settings null Time null SET_DEFAULT Set the default value SET Set to specified value DO_NOTHING No operation
models.OneToOneField()
  • One to many
    ForeignKey
  • Many to many
    ManyToManyField

To configure mysql

Configure database connection tool , Default is used sqlite3, Here it is modified as mysql, Logs are configured .

DATABASES = {

'default': {

# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'POST': '3306',
# Remove foreign key constraint 
'OPTIONS': {

"init_command": "SET foreign_key_checks = 0;",
},
}
}
LOGGING = {

'version': 1,
'disable_existing_loggers': False,
'handlers': {

'console': {

'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {

'django.db.backends': {

'handlers': ['console'],
'propagate': True,
'level': 'DEBUG',
}
},
}

Then generate the corresponding data table

  1. Generate migration file

python manage.py makemigrations

  1. Perform the migration

python manage.py migrate

Query statement

  1. all()
    Query all statements
In [1]: from app3.models import *
In [2]: users = UserBaseInfos.objects.all()
In [3]: print(users[0].username)
(0.000) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.000) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.000) SELECT `UserBaseInfo4`.`id`, `UserBaseInfo4`.`username`, `UserBaseInfo4`.`password`, `UserBaseInfo4`.`status`, `UserBaseInfo4`.`createDate` FROM `UserBaseInfo4` LIMIT 1; args=()
Background wall
  1. filter()
    Delete the specified value , Return a list of results
  2. get()
    Get a result set , Multiple data errors are returned .
 users = UserBaseInfos.objects.get(id=1)
print(users.username)
  1. exclude()
    Exclude qualified statements , Return result set
The operator meaning Example __gt() Greater than filter(age__gt=20)__gte() Greater than or equal to filter(age__gte=20)__lt() Less than filter(age__lt=20)__lte() Less than or equal to filter(age__lte=20)__in() In a list filter(age__in=[1,0])__contains() Fuzzy matching filter(age__contains=‘ Zhang ’)__year()/__month()/__day() Date match filter(createdate__year=2011)
  1. values()
    Extract the corresponding field

  2. distinct()

users = UserBaseInfos.objects.distinct().values(‘department’)

Add and update data

Use sava() Save updated data ,create() You can also add data .

users = UserBaseInfos.objects.get(id=1)
users.username = "Django.js"
users.save()

Delete data

delete() Method to delete data

F Functions and Q function

F Function can update fields , Use after update refresh_from_db()

user.salary = F(“salary”) + 1000

Q Function can support conditional query

filter(Q(age__gt=30)&Q(salary__gt=5000))

Run native SQL

Use django.db.models.Manager.raw() perform SQL, You can also execute with parameters SQL sentence , Use [] To pass in parameters .

users = UserBaseInfos.objects.raw("select * from UserBaseInfo4")
print(users[0].username)

Business

The transaction ASID characteristic : Atomicity 、 Uniformity 、 Isolation and persistence

Django There are mainly decorator mode and with sentence .

@transaction.atomic
def trans(request):
save_id = transaction.savepoint()
try:
---
transaction.savepoint_commit(save_id)
except:
transaction.savepoint_rollback(save_id)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved