Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Django 教程 --- Django 模型

Django 教程 --- Django 模型

作者头像
公众号---人生代码
发布于 2020-05-25 07:20:39
发布于 2020-05-25 07:20:39
2.2K00
代码可运行
举报
文章被收录于专栏:人生代码人生代码
运行总次数:0
代码可运行

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

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

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

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
from django.db import models
        
class ModelName(models.Model):
        field_name = models.Field(**options)

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 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
代码运行次数:0
运行
AI代码解释
复制
Python manage.py makemigrations

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 Python manage.py migrate

在Django管理界面中渲染模型

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
python manage.py shell

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> a = GeeksModel(
         title = “GeeksForGeeks”,
         description =A description here”,
         img = “geeks/abc.png”
         )
>>> a.save()

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> GeeksModel.objects.all()
<QuerySet [<GeeksModel: Divide>, <GeeksModel: Abbey Road>, <GeeksModel: Revolver>]>

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> a = GeeksModel.objects.get(id = 3)
>>> a.title = "Pop"
>>> a.save()

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
>>> a = Album.objects.get(id = 2)
>>> a.delete()

验证模型中的字段

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 删除。

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Excel图表学习48: 给两个系列之间添加阴影着色
图1所示的图表包含了两个折线图系列、两个堆积面积图系列。所使用的示例数据如下图2所示。
fanjy
2019/07/19
6.9K1
【Excel系列】Excel数据分析:时间序列预测
移动平均 18.1 移动平均工具的功能 “移动平均”分析工具可以基于特定的过去某段时期中变量的平均值,对未来值进行预测。移动平均值提供了由所有历史数据的简单的平均值所代表的趋势信息。使用此工具适用于变
数据科学社区
2018/02/02
6.9K0
【Excel系列】Excel数据分析:时间序列预测
Excel图表技巧04:强制图表坐标轴标签换行
这是在《Excel 2019宝典》中学到的一个技巧,让坐标轴标签数据强制换行,以达到更好的视觉效果。如下图1所示,水平坐标轴标签不仅显示了不同的销售区域,而且显示了该区域的销售量数值。这在不希望图表中显示数据标签时,这种方法很方便。
fanjy
2021/01/20
3K0
Excel图表技巧04:强制图表坐标轴标签换行
Excel图表学习59: 绘制时间线图
选择数据单元格区域A1:B17,单击功能区“插入”选项卡“图表”组中的“散点图”,得到原始图表如下图3所示。
fanjy
2019/12/12
2.9K0
Excel图表学习59: 绘制时间线图
Excel图表学习66:绘制动态的圆环/柱形图组合图表
导语:本文学习整理自chandoo.org,非常巧妙且具有想像力的Excel制图技巧。
fanjy
2020/07/29
2.1K0
Excel图表学习66:绘制动态的圆环/柱形图组合图表
Excel揭秘19:SERIES公式
SERIES公式控制着绘制Excel图表的数据,并且只在图表中有效,它不是真正的公式但可以像Excel公式一样在公式栏对其进行编辑。
fanjy
2019/10/16
5.4K0
Excel揭秘19:SERIES公式
精通Excel数组公式14:使用INDEX函数和OFFSET函数创建动态单元格区域
动态单元格区域是指当添加或删除源数据时,或者随着包含单元格区域的公式被向下复制时根据某条件更改,可以自动扩展或收缩的单元格区域,可以用于公式、图表、数据透视表和其他位置。
fanjy
2021/02/05
9.4K0
Excel图表学习64: 在Excel中仿制“关键影响因素图”
前言:下面的内容是在chandoo.org上学到的制图技术。Chandoo.org是一个很好的网站,上面分享了很多让人耳目一新的Excel技术知识。
fanjy
2019/12/27
4.3K0
Excel图表学习64: 在Excel中仿制“关键影响因素图”
Excel图表学习61: 编写一个给多个数据系列添加趋势线的加载宏
在《Excel图表学习60:给多个数据系列添加趋势线》中,我们手工给多个散点图系列添加了一条趋势线,如下图1所示。
fanjy
2019/12/24
1.9K0
Excel小技巧42:创建自动更新的图片数据
可以使用Excel内置的“照相机”功能,来创建自动更新的图片数据。如下图1所示,当工作表单元格区域B2:C6中的数据改变时,右侧文本框中图片的数据会自动更新。
fanjy
2020/07/07
1.2K0
新同事竟然把Excel折线图“掰”成晋升的台阶,瞬间俘获老板的心!
注意啦!注意啦!在文章《200篇Excel精华原创教程汇集!(文末免费领1899元课程福利!)》下留言,将有机会获赠价值500元的微课视频券,购课可抵消。赶紧戳上面蓝色文字链接,了解具体活动吧!
Piper蛋窝
2020/12/14
1.1K0
新同事竟然把Excel折线图“掰”成晋升的台阶,瞬间俘获老板的心!
Excel图表学习:创建子弹图
为了尽可能轻松地创建你的第一个图表,将新工作表的名称更改为“GG”,然后设置数据区域如图所示。在创建图表后,可以根据需要重命名工作表或移动数据。
fanjy
2022/11/16
4K0
Excel图表学习:创建子弹图
Excel图表学习70:按大小顺序的堆积柱形图
创建堆积柱形图时,列将按照系列添加到图表的顺序进行堆积。例如,绘制如下图1所示的简单数据时,系列A位于底部,系列B堆叠在A上,C堆叠在B上。这样的顺序忽略了每个类别中点的单个值。
fanjy
2021/07/12
4.7K0
Excel图表学习70:按大小顺序的堆积柱形图
Excel图表学习52: 清楚地定位散点图中的数据点
散点图是我们经常使用的一种图表类型,然而,当有许多个数据点时,往往很难弄清楚特定的数据点。其实,使用一些小技巧,我们能够很容易地定位散点图中特定的数据点,如下图1所示。
fanjy
2019/08/30
11.3K0
Excel图表学习72:制作里程碑图
1.复制原始数据并将其粘贴到指定位置,添加一个“位置”列(如下图2所示),以确定将里程碑显示在时间轴的上方还是下方。
fanjy
2021/07/30
5.2K0
精通Excel数组公式15:使用INDEX函数和OFFSET函数创建动态单元格区域(续)
导语:本文为《精通Excel数组公式14:使用INDEX函数和OFFSET函数创建动态单元格区域》的后半部分。
fanjy
2021/03/12
4.3K0
Excel实战技巧94: 显示过期事项、即将到期事项提醒
我们可以在工作表中安排计划,并让通过特殊显示来提醒已经过期的事项和即将到期的事项,以便让我们更好地安排工作。
fanjy
2020/12/08
6.8K0
Excel实战技巧94: 显示过期事项、即将到期事项提醒
Excel公式技巧77:排名次
很多人一开始就会想到Excel的“排序”功能。选取分数中的任意单元格,单击功能区“开始”选项卡“编辑”组中“排序和筛选——降序”命令,Excel会按分数由高到低排序,然后在列C中添加名次,如下图2所示。
fanjy
2021/01/06
9110
Excel图表学习69:条件圆环图
每个切片的颜色显示在图表左侧的工作表单元格区域内。根据单元格包含的字母“R”、“Y”或“G”将它们填充为红色、黄色和绿色。这在工作表中很容易做到,但在图表中没有像这样更改颜色的机制。
fanjy
2021/07/12
8K0
Excel图表学习69:条件圆环图
Excel图表学习:漏斗图2
在前面的文章《Excel图表学习67:4步绘制漏斗图》中,我们讲解了绘制漏斗图的技巧,今天,我们再举一例。这个示例来自于www.sumproduct.com。
fanjy
2022/11/16
2.2K0
Excel图表学习:漏斗图2
推荐阅读
相关推荐
Excel图表学习48: 给两个系列之间添加阴影着色
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验