Django 模型
Django 模型是 Django 用于创建表、它们的字段和各种约束的内置功能。简而言之,Django Models 是与 Django 一起使用的 Database 的 SQL。 SQL(结构化查询语言)很复杂,涉及许多不同的查询,用于创建、删除、更新或与数据库相关的任何其他内容。 Django 模型简化了任务并将表组织成模型。通常,每个模型都映射到一个数据库表。
本文围绕如何使用 Django 模型方便地在数据库中存储数据展开。此外,我们可以使用 Django 的管理面板来创建、更新、删除或检索模型的字段以及各种类似的操作。 Django 模型提供简单性、一致性、版本控制和高级元数据处理。模型的基础包括——
- 每个模型都是一个Python类,它是 django.db.models.Model 的子类。
- 模型的每个属性代表一个数据库字段。
- 有了这一切,Django 为您提供了一个自动生成的数据库访问 API;请参阅进行查询。
例子 -
Python3
from django.db import models
# Create your models here.
class GeeksModel(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
Python3
# 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
Python3
from django.contrib import admin
# Register your models here.
from .models import GeeksModel
admin.site.register(GeeksModel)
Python3
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
Django 将 Django 模型中定义的字段映射到数据库的表字段中,如下所示。
使用 Django 模型
要使用 Django 模型,需要有一个项目和一个在其中工作的应用程序。启动应用程序后,您可以在 app/models.py 中创建模型。在开始使用模型之前,让我们检查一下如何启动一个项目并创建一个名为 geeks.py 的应用程序
Refer to the following articles to check how to create a project and an app in Django.
- How to Create a Basic Project using MVT in Django?
- How to Create an App in Django ?
创建模型
句法
from django.db import models
class ModelName(models.Model):
field_name = models.Field(**options)
要创建模型,在 geeks/models.py 中输入代码,
Python3
# 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 基本上为预安装的应用程序生成 SQL 命令(可以在 settings.py 中的已安装应用程序中查看)和您在已安装应用程序中添加的新创建的应用程序模型,而 migrate 在数据库文件中执行这些 SQL 命令。
所以当我们跑步时,
Python manage.py makemigrations
将上面的模型创建为表的 SQL 查询已创建并
Python manage.py migrate
在数据库中创建表。
现在我们已经创建了一个模型,我们可以执行各种操作,例如为表创建一个 Row 或根据 Django 创建一个模型实例。要了解更多信息,请访问 – Django 基本应用模型 – Makemigrations 和 Migrate
在 Django 管理界面中渲染模型
要在 Django admin 中渲染模型,我们需要修改 app/admin.py。进入geeks app中的admin.py,输入以下代码。从models.py导入对应的模型,注册到admin界面。
Python3
from django.contrib import admin
# Register your models here.
from .models import GeeksModel
admin.site.register(GeeksModel)
现在我们可以检查模型是否已经在 Django Admin 中渲染了。 Django 管理界面可用于以图形方式实现 CRUD(创建、检索、更新、删除)。
要查看有关 django admin 中渲染模型的更多信息,请访问 – Render Model in Django Admin Interface
Django CRUD - 插入、更新和删除数据
Django 允许我们使用称为ORM(对象关系映射器)的数据库抽象API 与其数据库模型进行交互,即添加、删除、修改和查询对象。我们可以通过在项目目录中运行以下命令来访问 Django ORM。
python manage.py shell
添加对象。
要创建模型 Album 的对象并将其保存到数据库中,我们需要编写以下命令:
>>>> a = GeeksModel(
title = "GeeksForGeeks",
description = "A description here",
img = "geeks/abc.png"
)
>>> a.save()
检索对象
要检索模型的所有对象,我们编写以下命令:
>>> GeeksModel.objects.all()
, , ]>
修改现有对象
我们可以如下修改现有对象:
>>> a = GeeksModel.objects.get(id = 3)
>>> a.title = "Pop"
>>> a.save()
删除对象
要删除单个对象,我们需要编写以下命令:
>>> a = Album.objects.get(id = 2)
>>> a.delete()
要查看 Django 的 ORM(对象)的详细帖子,请访问 Django ORM – 插入、更新和删除数据
验证模型中的字段
Django 模型中的内置字段验证是为所有 Django 字段预定义的默认验证。每个字段都带有来自 Django 验证器的内置验证。例如, IntegerField 带有内置验证,它只能存储整数值并且也可以存储在特定范围内。
在极客应用的models.py文件中输入以下代码。
Python3
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
在 Django 上运行 makemigrations 和 migrate 并渲染上述模型后,让我们尝试使用字符串“ GfG is Best ”创建一个实例。
您可以在管理界面中看到,无法在 IntegerField 中输入字符串。同样,每个字段都有自己的验证。要了解有关验证的更多信息,请访问内置字段验证 – Django 模型
更多关于 Django 模型的信息——
- 使用 __str__函数更改对象显示名称 – Django 模型
- Django 模型中的自定义字段验证
- Django Python manage.py 迁移命令
- Django App Model – Python manage.py makemigrations 命令
- Django 模型数据类型和字段列表
- 如何使用 Django 字段选择?
- 覆盖保存方法 – Django 模型
基本模型数据类型和字段列表
模型中最重要的部分和唯一需要的部分是它定义的数据库字段列表。字段由类属性指定。这是 Django 中使用的所有字段类型的列表。
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 string filed for small to large-sized input 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.
字段选项
字段选项是赋予每个字段的参数,用于应用某些约束或将特定特征赋予特定字段。例如,向 CharField 添加参数 null = True 将使其能够在关系数据库中存储该表的空值。
以下是 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.