一個Django模塊是內置的功能,Django使用建立表,他們的田地,和各類約束。簡而言之,Django Models是與Django一塊兒使用的SQL數據庫。SQL(結構化查詢語言)很複雜,涉及許多不一樣的查詢,用於建立,刪除,更新或與數據庫有關的任何其餘內容。Django模型簡化了任務並將表組織到模型中。一般,每一個模型都映射到單個數據庫表。
本文圍繞如何使用Django模型方便地將數據存儲在數據庫中展開。此外,咱們可使用Django的管理面板來建立,更新,刪除或檢索模型的字段以及各類相似的操做。Django模型提供了簡單性,一致性,版本控制和高級元數據處理。模型的基礎包括–python
每一個模型都是一個子類的Python類django.db.models.Model
。shell
模型的每一個屬性表明一個數據庫字段。數據庫
經過全部這些,Django爲您提供了一個自動生成的數據庫訪問API。請參閱進行查詢。django
from django.db import models
# Create your models here.
class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
Django將Django模型中定義的字段映射到數據庫的表字段中,以下所示
app
要使用Django模型,須要在其中運行一個項目和一個應用程序。啓動應用程序後,能夠在app / models.py中建立模型。在開始使用模型以前,讓咱們檢查如何啓動項目並建立名爲geeks.py的應用程序ide
句法ui
from django.db import models
class ModelName(models.Model):
field_name = models.Field(**options)
要建立模型,請在geeks/models.py
輸入代碼中,this
# import the standard Django Model
# from built-in library
from django.db import models
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
last_modified = models.DateTimeField(auto_now_add = True)
img = models.ImageField(upload_to = "images/")
# renames the instances of the model
# with their title name
def __str__(self):
return self.title
每當咱們建立模型,刪除模型或更新咱們項目的任何models.py中的任何內容時。咱們須要運行兩個命令makemigrations
和migrate
。makemigrations基本上爲預安裝的應用程序(能夠在settings.py中的已安裝應用程序中查看)和生成的新模型(生成的模型)生成SQL命令,而後將其添加到已安裝的應用程序中,而migration則在數據庫文件中執行這些SQL命令。spa
Python manage.py makemigrations
建立要在表上方建立模型的SQL查詢,並版本控制
Python manage.py migrate
要在Django admin中渲染模型,咱們須要進行修改app/admin.py
。在geeks應用程序中轉到admin.py並輸入如下代碼。從models.py導入相應的模型並將其註冊到管理界面。
from django.contrib import admin
# Register your models here.
from .models import GeeksModel
admin.site.register(GeeksModel)
如今,咱們能夠檢查模型是否已在Django Admin中呈現。Django管理界面可用於以圖形方式實現CRUD(建立,檢索,更新,刪除)
Django使咱們可使用稱爲ORM(Object Relational Mapper)的數據庫抽象API與它的數據庫模型進行交互,即添加,刪除,修改和查詢對象。咱們能夠經過在項目目錄中運行如下命令來訪問Django ORM。
python manage.py shell
添加對象。
要建立相冊模型的對象並將其保存到數據庫中,咱們須要編寫如下命令:
>>> a = GeeksModel(
title = 「GeeksForGeeks」,
description = 「A description here」,
img = 「geeks/abc.png」
)
>>> a.save()
檢索對象
要檢索模型的全部對象,咱們編寫如下命令:
>>> GeeksModel.objects.all()
<QuerySet [<GeeksModel: Divide>, <GeeksModel: Abbey Road>, <GeeksModel: Revolver>]>
修改現有對象
咱們能夠以下修改現有對象:
>>> a = GeeksModel.objects.get(id = 3)
>>> a.title = "Pop"
>>> a.save()
刪除對象
要刪除單個對象,咱們須要編寫如下命令:
>>> a = Album.objects.get(id = 2)
>>> a.delete()
Django模型中的內置字段驗證是全部Django字段預約義的默認驗證。每一個字段都帶有來自Django驗證程序的內置驗證。例如,IntegerField帶有內置驗證,該驗證只能存儲整數值,而且也能夠存儲特定範圍內的值。
在geeks應用models.py
文件中輸入如下代碼
from django.db import models
from django.db.models import Model
# Create your models here.
class GeeksModel(Model):
geeks_field = models.IntegerField()
def __str__(self):
return self.geeks_field
在運行makemigrations並在Django上遷移並渲染以上模型後,讓咱們嘗試使用字符串「 GfG is Best 」 建立一個實例。
模型的最重要部分和模型惟一須要的部分是它定義的數據庫字段的列表。字段由類屬性指定。這是Django中使用的全部Field類型的列表。
FIELD NAME | DESCRIPTION |
---|---|
AutoField | It An IntegerField that automatically increments. |
BigAutoField | It is a 64-bit integer, much like an AutoField except that it is guaranteed to fit numbers from 1 to 9223372036854775807. |
BigIntegerField | It is a 64-bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. |
BinaryField | A field to store raw binary data. |
BooleanField | A true/false field. The default form widget for this field is a CheckboxInput. |
CharField | It is a date, represented in Python by a datetime.date instance. |
DateField | A date, represented in Python by a datetime.date instance |
It is used for date and time, represented in Python by a datetime.datetime instance. | |
DecimalField | It is a fixed-precision decimal number, represented in Python by a Decimal instance. |
DurationField | A field for storing periods of time. |
EmailField | It is a CharField that checks that the value is a valid email address. |
FileField | It is a file-upload field. |
FloatField | It is a floating-point number represented in Python by a float instance. |
ImageField | It inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. |
IntegerField | It is an integer field. Values from -2147483648 to 2147483647 are safe in all databases supported by Django. |
GenericIPAddressField | An IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or 2a02:42fe::4). |
NullBooleanField | Like a BooleanField, but allows NULL as one of the options. |
PositiveIntegerField | Like an IntegerField, but must be either positive or zero (0). |
PositiveSmallIntegerField | Like a PositiveIntegerField, but only allows values under a certain (database-dependent) point. |
SlugField | Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. |
SmallIntegerField | It is like an IntegerField, but only allows values under a certain (database-dependent) point. |
TextField | A large text field. The default form widget for this field is a Textarea. |
TimeField | A time, represented in Python by a datetime.time instance. |
URLField | A CharField for a URL, validated by URLValidator. |
UUIDField | A field for storing universally unique identifiers. Uses Python’s UUID class. When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32). |
Django還定義了一組表示關係的字段
FIELD NAME | DESCRIPTION |
---|---|
ForeignKey | A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. |
ManyToManyField | A many-to-many relationship. Requires a positional argument: the class to which the model is related, which works exactly the same as it does for ForeignKey, including recursive and lazy relationships. |
OneToOneField | A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the 「reverse」 side of the relation will directly return a single object. |
字段選項是賦予每一個字段的自變量,用於對某些字段施加某種約束或賦予其特定的特性。例如,向null = True
CharField 添加參數將使其可以在關係數據庫中存儲該表的空值。
這是CharField可使用的字段選項和屬性。
FIELD OPTIONS | DESCRIPTION |
---|---|
Null | If True, Django will store empty values as NULL in the database. Default is False. |
Blank | If True, the field is allowed to be blank. Default is False. |
db_column | The name of the database column to use for this field. If this isn’t given, Django will use the field’s name. |
Default | The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. |
help_text | Extra 「help」 text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
primary_key | If True, this field is the primary key for the model. |
editable | If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True. |
error_messages | The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. |
help_text | Extra 「help」 text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. |
verbose_name | A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. |
validators | A list of validators to run for this field. See the validators documentation for more information. |
Unique | If True, this field must be unique throughout the table. |