前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Django 教程 --- Django 模型

Django 教程 --- Django 模型

作者头像
公众号---人生代码
发布2020-05-25 15:20:39
2.1K0
发布2020-05-25 15:20:39
举报
文章被收录于专栏:人生代码人生代码

一个Django模块是内置的功能,Django使用创建表,他们的田地,和各种约束。简而言之,Django Models是与Django一起使用的SQL数据库。SQL(结构化查询语言)很复杂,涉及许多不同的查询,用于创建,删除,更新或与数据库有关的任何其他内容。Django模型简化了任务并将表组织到模型中。通常,每个模型都映射到单个数据库表。 本文围绕如何使用Django模型方便地将数据存储在数据库中展开。此外,我们可以使用Django的管理面板来创建,更新,删除或检索模型的字段以及各种类似的操作。Django模型提供了简单性,一致性,版本控制和高级元数据处理。模型的基础包括–

每个模型都是一个子类的Python类django.db.models.Model

模型的每个属性代表一个数据库字段。

通过所有这些,Django为您提供了一个自动生成的数据库访问API。请参阅进行查询。

代码语言:javascript
复制
from django.db import models
  
# Create your models here.
class GeeksModel(models.Model): 
    title = models.CharField(max_length = 200)
    description = models.TextField()

Django将Django模型中定义的字段映射到数据库的表字段中,如下所示

使用Django模型

要使用Django模型,需要在其中运行一个项目和一个应用程序。启动应用程序后,可以在app / models.py中创建模型。在开始使用模型之前,让我们检查如何启动项目并创建名为geeks.py的应用程序

建立模型

句法

代码语言:javascript
复制
from django.db import models
        
class ModelName(models.Model):
        field_name = models.Field(**options)

要创建模型,请在geeks/models.py输入代码中,

代码语言:javascript
复制
# 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中的任何内容时。我们需要运行两个命令makemigrationsmigrate。makemigrations基本上为预安装的应用程序(可以在settings.py中的已安装应用程序中查看)和生成的新模型(生成的模型)生成SQL命令,然后将其添加到已安装的应用程序中,而migration则在数据库文件中执行这些SQL命令。

代码语言:javascript
复制
Python manage.py makemigrations

创建要在表上方创建模型的SQL查询,并

代码语言:javascript
复制
 Python manage.py migrate

在Django管理界面中渲染模型

要在Django admin中渲染模型,我们需要进行修改app/admin.py。在geeks应用程序中转到admin.py并输入以下代码。从models.py导入相应的模型并将其注册到管理界面。

代码语言:javascript
复制
from django.contrib import admin
    
# Register your models here.
from .models import GeeksModel
    
admin.site.register(GeeksModel)

现在,我们可以检查模型是否已在Django Admin中呈现。Django管理界面可用于以图形方式实现CRUD(创建,检索,更新,删除)

Django CRUD –插入,更新和删除数据

Django使我们可以使用称为ORM(Object Relational Mapper)的数据库抽象API与它的数据库模型进行交互,即添加,删除,修改和查询对象。我们可以通过在项目目录中运行以下命令来访问Django ORM。

代码语言:javascript
复制
python manage.py shell

添加对象。 要创建相册模型的对象并将其保存到数据库中,我们需要编写以下命令:

代码语言:javascript
复制
>>> a = GeeksModel(
         title = “GeeksForGeeks”,
         description = “A description here”,
         img = “geeks/abc.png”
         )
>>> a.save()

检索对象 要检索模型的所有对象,我们编写以下命令:

代码语言:javascript
复制
>>> GeeksModel.objects.all()
<QuerySet [<GeeksModel: Divide>, <GeeksModel: Abbey Road>, <GeeksModel: Revolver>]>

修改现有对象 我们可以如下修改现有对象:

代码语言:javascript
复制
>>> a = GeeksModel.objects.get(id = 3)
>>> a.title = "Pop"
>>> a.save()

删除对象 要删除单个对象,我们需要编写以下命令:

代码语言:javascript
复制
>>> a = Album.objects.get(id = 2)
>>> a.delete()

验证模型中的字段

Django模型中的内置字段验证是所有Django字段预定义的默认验证。每个字段都带有来自Django验证程序的内置验证。例如,IntegerField带有内置验证,该验证只能存储整数值,并且也可以存储特定范围内的值。 在geeks应用models.py文件中输入以下代码

代码语言:javascript
复制
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 = TrueCharField 添加参数将使其能够在关系数据库中存储该表的空值。 这是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.

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 CryptoCode 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用Django模型
    • 建立模型
      • 在Django管理界面中渲染模型
        • Django CRUD –插入,更新和删除数据
          • 验证模型中的字段
            • 关系字段
        • 基本模型数据类型和字段列表
        • 栏位选项
        相关产品与服务
        数据库
        云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档