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

Getting Started with Django 1

編輯:Python

文章目錄

  • 一、Django中的Models
    • 1.model簡介
    • 2.model設計
    • 3.orm
    • 4.models的屬性與字段(field)
    • 5.Meta類屬性
  • 二、數據庫的操作
    • 1.查詢
    • 2.增加
    • 3.刪除
    • 4.排序查詢
    • 5.切片


提示:以下是本篇文章正文內容.

一、Django中的Models

1.model簡介

  • [1] 通常情況,一個Models對應數據庫的一張表
  • [2] Django中Models以類的形式表現
  • [3] 它包含了一些基本字段以及數據的一些行為
  • [4] We only need to operate inside the class,就可以操作數據庫、表,不需要直接使用SQL語句
  • [5] We create data tables by creating classes,So the operation of the database,Both operate on classes and objects of classes,而不使用sql語句
  • [6] ORM對象關系映射,Implemented the mapping of objects and databases,隱藏了數據訪問的細節,不需要編寫SQL語句

代碼如下:

form django.db import models
class Modelname(models.Model):
# Create a model class and inherit from itmodels.Model
# A class is a table in a database
field1 = models.XXXfield(max_lenge=10,verbose_name='haha'
field = models.XXXfield()
class Meta():
# Define a description for this class
verbose_name = XXX
# Do not add this word to oursverbose_name在adminIt will be added automaticallys
verbose_name_plural = XXX

2.model設計

  1. 設計Model的時候,可以繼承自Models.model或者AbstractUser,AbstractUseris the built-in user class,When you want to inherit the built-in user model and extend it,就使用它,Modelsis a generic model class,All custom models need to inherit this.
  2. AbstractUser要記得在setting.py裡面加上AUTH_USER_MODEL = ‘users.UserProfile’
  3. 設計表的時候,First share which tables are needed,The key is to analyze the relationship:實體1 <對於關系> 實體2,The table relationship is one-to-many,Or more to one and so on,You need to analyze and define foreign keys yourself
  4. The second step in designing the table is to design the specific fields,Whether the type of each field is required.

Usually one can be added to our tableadd_time屬性,Used to record when this record was added,

from datetime import datetime
class BaseModel(models.Model):
add_time = models.DateTimeField(default=datetime.now,verbose_name="添加時間"
class Meta:
# Djangowill help us create this table
abstract = True
class Course(BaseModel):
'''Write properties here'''
'''外鍵'''
class Lesson(BaseModel):
course = models.ForeignKey(Course,on_delete=models.CASCADE)
'''It must be noted here that the first parameter is the foreign key to be associated,
The second parameter must be written,Used to set whenCourse被刪除的時候,
How to deal with foreign keys,CASCADEIndicates if the corresponding course is deleted,then the foreign key
Records are also deleted in cascade,而一種SET_NULLAttributes refer to after the course is deleted
This foreign key column is left blank,它必須和```null = True,blank = True```
連用,Otherwise, how can it be empty

3.orm

Python、PHP、Java是一種開發語言,而MySQL、SQL ServerThe database language is used,How to achieve interoperability between different languages.
SQLLanguages ​​include data definition languagesDDL、數據控制語言DCL、數據查詢語言DQL、數據操作語言DML等,例如INSERT、DELETE、SELECT、UPDATE操作.
作為開發人員,You should focus on writing core business code,You shouldn't spend too much effort dealing with database languages.
ORM(Object-Relational Mapping,對象關系映射)Technology can be seen as a bridge between developers and databases,Used to implement databases and
Mapping between programming languages,本質上來看,ORM就是將SQLOperations and programming language operations made a translation.
通過ORMtechnology to operate the database,So that developers do not need to contactSQL語句,And directly manipulate the properties and methods of the object,大大提高了開發效率.

orm的功能

  • 映射技術:數據類型映射、類映射、關系映射.例如,Each database table corresponds to the class of the development language,Each data field corresponds to a property in the class.
  • CRUD操作:CRUDThat is, add, delete, check, and modify operations,在SQL語句中通過Insert、Select、Update、Delete來實現,在ORMrequired in the library
    through the corresponding function to achieve,例如Django ORM通過get、filter、save、delete函數進行操作.
  • 緩存優化:(惰性操作)The data queried from the database is stored in memory in the form of class objects,For anytime extraction;The database is executed only when the query result is really neededselect操作,而不是在ORMQuery the database when the query command is executed.

4.models的屬性與字段(field)

AutoField:An auto-incrementing integer field,通常用於主鍵
CharField:字符串字段,Used to enter shorter characters,對應與HTML裡面<input type='text'>
TextField:文本字段,Used to enter more characters,對應html標簽 <input type = "textarea">;
EmailField:郵箱字段,For input withEmail格式的字符
DateFiled
TimeFiled
DateTimeField:日期字段,Time input is supported
ImageField:Used to upload pictures and verify the legitimacy of pictures,需定義upload_to參數,Installation is required to use this fieldpython pillow等圖片庫
IntegerField:整數字段,Used to hold integer information

屬性

primary_key:設置True or False,Defines whether this field is the primary key
default:設置默認值,Default text can be set、時間、圖片、時間等
null:設置True or False,Whether database fields are allowedNull,默認為False
blank:設置True or False,Defines whether to run without user input,默認為False;若為True,Then the user can leave this field blank
max_length:設置默認長度,一般在CharField、TextField、EmailFieldetc. Text field settings
verbose_name:Set the name of this field,All fields can be set,在WebThe page will be displayed(For example, display English as Chinese)
choices:Set an optional value for this field,The value of this field is a tuple of two-dimensional elements;元素的第1value is the actual stored value,第2個值為HTML頁面顯示的值
upload_to:設置上傳路徑,ImageField和FileFieldfield requires this parameter to be set,如果路徑不存在,會自動創建

5.Meta類屬性

1. verbose_name:設置對象名稱(例如usecms),若沒有設置,The default is the lowercase tokenized form of the class name,例如類名為CamelCase會被轉換為camel case;
2.verbose_name_plural:Set object name plural(例如usercms),General settings followverbose_name一樣,verbose_name_plural=verbose_nameOtherwise, it will be added by defaults;
3. db_table:Set the mapped data table name,默認為“應用名_模型名”,That is where the model is usedappThe name of the model plus the name of this model class
4.proxy:設置True or False,Set whether this model and all sub-models that inherit this model are proxy models;
5. abstract:設置True or False,Set whether this model class is an abstract base class;If it is an abstract base class,Then this table will not be created,This table is used as a base class to be inherited by other tables

二、數據庫的操作

1.查詢

modelname.object.all()取出所有的數據
modelname.object.get(pk=id)Query the data that meets the filter criteria(一條),If more than one item is found or none is found, an error will be reported
modelname.object.filter(....)Query the datasets that meet the filter criteria(一條或者多條),Returns an empty list if the object does not exist,而不會報錯.
ModelName.Objects.exclude( )Returns datasets that do not meet the filter criteria

2.增加

代碼如下:

#Regular assignment increases
field1 = models.CharField()
field2 = modelsEmailField()
modelname.object.save()
#or 利用create方法
modelname.object.create(field1=models.CharField())
user_cms = UserCMS.objects.create(username=username, password=password)

3.刪除

Add it after the query method.delete()

4.排序查詢

代碼如下:

ModelName.Objects.all( ).order_by('xxx')

5.切片

代碼如下:

#ModelName.Objects.all( ).order_by('xxx')[a:b]
all_interviews = Interview.objects.all().order_by('-read_counts')[:6]
recommended_interviews = Interview.objects.filter(company=recommended_tag).exclude(id=int(interview_id)).order_by('-read_counts')[:3]


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