🦖
Wii
  • 原码补码反码
  • Archive
    • Job
      • Learn
      • 算法
      • Company
        • HundunDaxue
      • Company
      • 基础
        • 原码补码反码
      • 项目经验
      • require
    • Hobbies
      • Physics
        • 上帝粒子
        • 概述
        • 时间
      • Movie
        • MovieList
      • Psychology
        • Psychology
        • Chenli
          • ChenliLivingRoom
      • Philosophy
        • Philosophy
        • Conceptions
        • 导言
      • Travel
        • City
          • 昆明
          • 沈阳
        • articles-check-list
      • Sports
        • Swimming
        • Skiing
      • Earth
        • Ocean
          • Biology
      • Read
        • BookList
        • 道德经
        • BookToRead
      • Music
        • sort
      • PickUp
        • SoldiersSortie
    • Care
      • Illness
        • cold
        • 腹泻
        • acne
        • EmotionalControl
        • 咽炎
        • Anemia
      • Foods
        • 破壁机
          • 食谱
      • I
      • WishList
      • WithL
        • MF
          • LY
    • Wfw
      • QA
    • Mac
      • Brew
        • 软件安装目录
      • Usage
        • RunScriptAsRootOnBoot
        • Mac-Config
      • 制作启动U盘
      • Software
        • IntelliJIDEALicenseServer
          • run-license-server
    • PlantUML
      • plantuml
    • Windows
      • Windows常用命令
      • PowerShell
        • powershell 命令
      • Cmder
      • MTP服务驱动无法安装
    • English
      • 英语阅读2016-07-29
      • 英语阅读2016-08-11
    • Tools
      • Plantuml
        • Setup
      • Eclipse
        • Eclipse
        • Eclipse常见问题
      • CommonHotkey
      • Jetbrain
        • JetbrainIDEs
      • VSCode
      • SublimeText
        • 格式化代码
    • I
      • WHATIAM
    • Device
      • Netgear
        • Astrill
      • RPi
        • Hardware
    • AwesomeSoftware
    • RESTful
    • Course
      • 自然辩证法
        • 我国在生态文明建设中存在的困境及解决对策
        • 工程师应该具有的基本道德素养
        • 科学文化与人文文化的关系
      • 英语写作
        • Description
      • 分布式系统
        • 分布式系统概论
      • 英语口语
        • 辩论赛
    • CloudLib
      • 推荐0.1
    • Project
      • README
        • emq
          • Emq架构
        • 启动
        • Hikvision
          • TimeSetting
    • Efficient
    • Neu
      • IpCamera
        • live
        • ffmpeg
    • Matlab
      • Matlab 2016b 破解
    • SchoolWork
      • 学术道德与学术规范
    • git-push
  • Coding
    • Design Pattern
      • 设计模式笔记_四_工厂模式
      • 设计模式笔记_六_命令模式
      • 设计模式笔记_三_装饰者模式
      • 设计模式入门
      • 设计模式笔记_八_模板方法模式
      • 设计模式笔记_一_策略模式
      • 设计模式笔记_五_单件模式
      • 设计模式笔记_七_适配器模式与外观模式
      • 设计模式笔记_二_观察者模式
      • 设计模式笔记_十_状态模式
      • 设计模式笔记_九_迭代器与组合模式
    • C++
      • Notes
        • Practice
          • Logger
        • Thread
          • PosixThreadPrograming
          • ThreadNote
        • Features
          • FuturePromise
          • Lambda
        • STL
          • STLPractice
          • 迭代器
          • UnorderedMapSet
          • Containor
          • STL
          • Vector
        • CMake
          • Startup
          • CMakeExample
          • CMake
          • CMakeUsage
          • CMakeKnowledge
        • Mutex
        • Gdb
          • Gdb
        • LanguageNotes
          • Pointer
          • String
          • Functions
          • 友元
          • IO
          • OOP
          • Exceptions
          • Basic
          • 初始化
          • Random
          • 模板函数
        • Glog
          • glog
        • Thrift
          • Thrift
        • Valgrind
          • valgrind
        • 动态库 & 静态库
        • BookNotes
          • AboutC++
        • LRvalues
      • map
      • protobuf
      • Build
      • Seastar
        • Notes
          • std::move
          • Introduce
          • Install
            • BuildAndInstall
          • Steps
          • cmd
      • Tricks
      • Map
      • CommonOperation
      • FreqAlgorithm
    • Tools
      • Git
        • GitExamples
        • GitUsage
        • GitKnowledge
        • GitIgnoreExample
        • DeleteBigFileFromHistory
      • Vim
        • VimTips
        • 安装
        • Vim-Usage
        • Plugins
        • Vim-Config
      • SVN
        • svn服务器搭建
        • svn
    • Scala
      • Notes
        • Scala-模式匹配
        • Scala: 隐式
        • Scala-符号语法
        • Scala-函数
        • Scala面向对象编程
        • Scala 函数式编程
        • Scala:zipWithIndex
        • Future
        • Scala-语法
        • Scala-基础
      • DateTime
      • 规范
    • Python
      • Notes
        • BookNotes
          • 生成器
          • 垃圾回收机制
          • 数据结构
          • 数据类型
          • RegularExpression
          • 迭代器
          • NetworkProgramming
          • 函数式编程
          • 上下文管理器
          • PythonDataModel
          • 运算符
          • 魔术方法
          • 面向对象
          • 装饰器
          • 模块
          • MultithreadProgramming
          • 异常
          • 函数
        • Modules
          • stack
          • Datetime
          • shutil:文件操作
          • logging
          • urllib
          • Re
          • 容器数据类型
          • TypeError
          • str
          • queue
          • urllib-and-requests
          • Exception
          • path
          • os
        • Others
          • PythonSerialization
          • Python函数的docstring
          • PIL
          • type-cast
          • operations
          • Python-类
          • 组及命名组匹配
          • Package
          • jieba分词
          • logging模块
          • Python
          • print
        • Examples
          • 文件读取写入
          • 命名
          • 递归更改文件为windows合法名称
          • 定制命令行运行方式
          • Python处理Excel文件(xlsx文件格式)
          • 读取ini配置文件
          • tor代理
          • 添加父目录到Path
        • CommonTips
        • CodingStandards
          • python注释
          • PEP-8
      • Django
        • DjangoDocs
          • making queries
          • 设置media路径
          • models
          • manage.py使用
          • template
          • view
          • forms
          • setting.py 文件配置说明
          • nginx-deploy
          • 使用pymysql
          • 自定义tags和filters
          • admin-interface
        • DjangoRestFramework
          • Customer Permissions
          • Serializers
          • FileField绝对路径问题
          • DjangoRestFrameworkNotes
          • ViewSet
        • DjangoNotes
          • Model对象转化为Dict
          • QuerySet
      • Scrapy
        • Scrapy
        • Spider
        • Scrapy安装出错
        • Selector
        • Scrapy模拟登陆
      • Job
        • 字典
      • Pandas
        • pandas
        • PandasExamples
      • VirtualEnv
        • virtualenv
      • Numpy
        • NumpyUsage
        • numpy
      • Matplotlib
        • MatplotlibNotes
        • MatplotlibUsage
      • Database
        • 获取表字段
      • Pip
        • 更改源
      • Scipy
        • scipy
    • Web
      • 插件
        • bootstrap-table
          • bootstrap-table
        • bootstrap
          • 模态框
        • requirejs
          • requirejs
        • toastr
          • toastor
      • Koa
        • Notes
          • KoaNotes
      • SCSS
        • 常用标签
        • Watch
      • Vue
        • Notes
          • 路由
          • 参考
          • 组件
          • Plugins
          • Vuex
          • StartUp
      • 样式
      • CSS
        • CSS
      • 排版
      • Notes
        • 跨域访问
      • Hexo
        • HexoUsage
      • Nodejs
        • Koa
          • jest
          • ParamValidate
        • 仓库镜像
      • Express
        • Express
        • Jade
          • Jade
      • Canvas
        • Canvas
    • Basic
      • Data Structure
        • Heap
          • Heap
        • Tree
          • Tree
        • Benchmark
          • map
      • Boolean
      • MultithreadProgramming
      • Software Engineering
        • UML
          • UML
      • OOP
      • 介绍
    • Antlr
      • Example
      • Grammar
      • Antlr
    • Java
      • Library
        • MyBatis
          • generator
            • mybatis配置详解
          • mybatis-获取自增ID
          • mybatis
          • problems
        • log4j
          • Usage
      • Maven
        • MavenUsage
        • Maven
        • MavenProject
        • 项目RUL路径问题
        • MavenPom
        • Settings
        • PomCommon
        • PomExample
      • Notes
        • Features
          • Reflect
          • Java函数式编程
          • toMap
          • Closeable & AutoCloseable & Flushable
          • Annotations
        • Common
        • ThinkingInJava
          • 控制执行流程
          • 接口
          • 复用类
          • 内部类
          • 操作符
          • 访问权限控制
          • 一切都是对象
          • 多态
          • 初始化与清理
          • 对象导论
        • SwordToOffer
        • Network
        • Thread
          • ThreadPool
        • Basic Library
        • Collections
          • List Interface
        • CommandLine
        • Project Common
        • JavaLang
      • JVM
        • Monitor
          • Jmap
          • mat
          • Jstat
          • Monitor
        • Notes
          • JVM
        • GC
          • GC
          • Shenandoah
            • Shenandoah
        • JVM
    • Algorithm
      • Code
        • LeetCode
          • Python
            • 0000-0050
              • 0005
              • 0030
        • SwordToOffer
          • SwordToOffer
      • AlgorithmSummary
      • Classics
        • string
          • KMP
        • Other
          • FullPermutation
        • 链表
        • Sort
          • Sort
      • Other
        • README
      • Notes
        • Math
          • 两点计算直线方程
    • Go
      • Notes
        • Go Project Layout
        • Install
        • Startup
      • Basic
        • Startup
        • Types
    • JavaScript
      • MasonryLayouts
      • jquery
      • Notes
        • Promise
      • js
    • Android
      • SDK
        • 打开SDK Manager
    • C#
      • WebBrowser
      • c#图片
      • 跨线程访问控件
    • Knowledge
      • 函数式编程
      • 设计框架
    • Rules
      • Rules
    • React
      • ReactNative
        • React Native Navigation
        • 打包Apk
        • ReactNative
      • React
        • README
    • RegExp
      • 正则表达式
    • WeChatApp
      • 登陆
    • Node
      • Notes
        • StartUp
  • Computer Science
    • ICS Security
      • 工控网络
      • 工业控制系统
      • HoneyPot
        • 蜜罐软件
          • Honeyd
      • 工业以太网
      • CNVD
        • 环境及依赖
      • 现有蜜罐系统及工具
      • 工控系统安全措施
      • 蜜网
      • 蜜罐
      • 工控安全相关概念
    • Data Analysis
      • Data Mining
        • Notes
          • Data_Preprocessing
          • 数据预处理
          • 认识数据
          • Mining_Modeling
          • 数据探索
          • Python_Data_Mining_Functions
          • Python数据分析平台搭建
          • Reference_Books
          • 数据分析与挖掘基础
        • Jupyter
          • show
            • mean
      • Hadoop
        • Hadoop权威指南:数据完整性
        • Hadoop权威指南: I/O操作序 - 列化
        • Hadoop权威指南-从Hadoop URL读取数据
        • Hadoop权威指南:FSDataInputStream对象
        • HDFS常用命令
        • Hadoop权威指南:HDFS-数据流
        • Hadoop权威指南:通过distcp并行复制
        • Hadoop权威指南:压缩
        • Hadoop权威指南:HDFS-Hadoop存档
        • 解决使用Idea/Eclipse编写Hadoop程序包依赖问题
        • HDFS
        • Hadoop-命令
        • 简单javaHadoop应用程序从打包到提交运行
        • Hadoop权威指南:HDFS-写入数据
        • Hadoop权威指南:HDFS-目录,查询文件系统,删除文件
        • HadoopInputFormat-OutputFormart
        • Hadoop-HDFS命令行接口
        • Hadoop权威指南-MapReduce应用开发
        • Linux下使用javac编译Hadoop程序
        • Hadoop权威指南:通过FileSystem API读取数据
        • Hadoop专有数据类型
      • Spark
        • Spark计算模型
        • Spark-入门二
        • 安装Hadoop及Spark(Ubuntu 16.04)
        • Spark:核心概念简介
        • Spark:控制日志输入
        • Spark - RDD编程
        • Spark工作机制
        • Spark-一个独立应用
        • Spark
        • Spark:使用Spark Shell的两个示例
    • Linux
      • Notes
        • BuildInCommand
          • ls
          • ip
          • ftp
          • 目录栈操作
          • scp
          • expect
            • expect示例
            • expect手册
            • expect笔记
          • ps
          • vsftpd
          • wget
          • 压缩程序
            • zip_unzip
            • tar
            • p7zip
          • 部署web服务
          • avidemux
          • cat
          • Awk
          • find
          • pssh使用
          • grep
          • sed
          • 路径
          • 通用命令
          • 安装JDK
          • 进程管理
          • network
          • rsync
          • cron
          • 示例
          • 用户管理
          • supervisor
        • Common
        • TestFileProcess
          • 替换文件内容
        • Commonds
        • Permissions
      • Ubuntu
        • Ubuntu 服务器配置部署
        • Ubuntu笔记
        • Ubuntu网络配置
        • Ubuntu 16.04 几个国内源
      • Script
        • ShellProgramming
        • ShellExamples
        • ShellCommands
      • CentOS
        • Centos笔记
        • 源
        • CentOS-Network-Config
        • CentOS-Security
      • Squid
        • BuildByDocker
        • Squid
      • Problem
        • 常见错误
      • Linux
        • Linux-c-cpp
        • Linux
        • Linux-NetworkProgramming
      • Codes
        • cron-test-01
      • Software
        • Shortcut key
        • Anaconda
      • Make
        • tricks
      • Deepin
        • 安装docker
      • SRE
        • CommonCommand
    • Cloud Computing
      • OpenStack
        • Fuel离线安装OpenStack
        • 验证网络
        • OpenStackNotes
    • Network
      • TCP/IP
      • 套接字
      • OSI模型
    • Data mining
      • StartUp
    • Machine Learning
      • Notes
        • 决策树学习-周志华
        • 神经网络-周志华
        • 概念学习和一般到特殊序
        • MachineLearningProblems
        • Math
          • 概率论与数理统计
          • 数学概念
          • KKT条件
          • 最优化问题
          • 优化算法
          • 最小二乘
        • 模型评估与选择
        • 引言
        • 过拟合处理
        • StatisticalLearningMethod
          • 统计学习方法概论
          • 感知机
        • 评估假设
        • Code
          • FeatureEngineering
            • Iris
        • 概念
        • SVM
        • FeatureEngineering
        • 神经网络
        • 决策树学习
        • MachineLearningKnowledge
        • 线性模型
        • 术语概念
        • 拉格朗日乘子法
      • route
      • Jupyter
        • JupyterUsage
      • Anaconda
        • AnacondaUsage
      • Coursera
        • Week01
      • ScikitLearn
        • FitTransform
        • Preprocessing
      • Octave
        • Octave
    • Search
      • Lucene
        • Api
        • Concepts
    • Virtualization Tech
      • Docker
        • dockerNetwork
        • Ubuntu
        • DockerUsage
        • Mac OS
    • Database
      • MySQL
        • Mysql Cluster
        • mysql-cluster
        • mysql
      • 部署phpmyadmin
      • SQL
      • SQL
        • SQLStatement
    • Concepts
      • Other
      • Mohout
      • LDA
    • Distributed System
      • Concepts
        • TODO
        • TODO
    • Recommend System
      • DataPipline
        • DataBus
        • 系统
    • OS
      • OS-Code
      • Notes
        • Introduce
        • ProcessManagement
        • Kernel
    • Deep Learning
      • Code
        • README
      • Notes
        • Conceptions
        • 神经网络
        • LeNet5
        • CNN
      • Tensorflow
        • Notes
          • Tensorflow
          • tensorflow开始
        • Anaconda
    • Media
      • FFmpeg
        • LiveStream
          • run
    • Spider
      • Selenium
        • Selenium
    • IoT
      • emq
        • Authentication
    • Big Data
      • Hadoop
        • MR 作业
  • Architecture
    • Storage
      • Mongodb
        • Mongodb
        • Failed to unlink socket file
      • Pegasus
        • Pegasus
        • ShellTools
      • Rocksdb
        • RocksJava
        • RocksDB
        • 本地缓存
      • Redis
        • Install
        • RedisUsage
      • 基本要素
      • HBase
        • HBase
    • MQ
      • Kafka
        • VersionCompare
        • Deploy
        • cppkafka
        • CommandLineTools
        • OffsetManage
        • Attentions
        • Notes
        • QA
    • Framework
      • Java
        • Dubbo
          • Annotation
          • 简介
        • Spring
          • SpringTest
          • 常见错误
          • TransactionRollback
          • FileUpload
          • SpringMVCNote
          • IoC
          • Start
          • Notes
            • Config
          • Spring
          • springmvc
          • Modules
        • Rose
          • Get request body
        • Netty
          • Netty
        • SpringBoot
          • SpringBoot
      • Esper
        • Documents
          • Keyed Segmented Context
          • 01 - Getting Started
          • 02 - Event Representations
          • 03 - Processing Modal
      • Swagger
        • Swagger
    • RPC
      • Thrift
        • Notes
          • Set fields
          • ThriftTyps
        • BuildFromSource
        • ThriftUsage
        • Install
      • ProtocolBuffer
        • 减少内存拷贝
        • UsageExample
        • Arena
        • ProtocolBuffer
    • Distribution
      • CAP
    • Streaming
      • Spark
        • Init
      • MapReduce
      • Spark
    • Nginx
      • Nginx knowledge
      • nginx-configurtion
      • 403
      • nginx解析php文件时502
    • Governance
      • Consul
      • Zookeeper
        • Zookeeper
      • MicroServiceArchitecture
      • 依赖
    • Conceptions
      • CloudNative
    • Kibana
      • Query
    • Performance Optimizaition
      • Notes
        • Conceptions
        • CPUAffinity
  • Math
    • Probability Theory
      • 一些概率分布
    • Statistics
      • 统计量与估计量
    • Other
      • 排列组合
  • Tools
    • Markdown
      • syntax
    • Jetbrains
      • Jetbrains
    • Zsh
      • Install
  • TODO
由 GitBook 提供支持
在本页
  • 文档版本
  • 简单实例
  • 定义
  • 使用
  • 主键
  • 获取所有项
  • 删除所有
  • 关系(Relationships)
  • 多对一关系(Many-to-one relationships)
  • 多对多关系(Many-to-many relationships)
  • Migrations
  • 生成变更
  • 应用变更
  • 字段
  • datetimefield
  • user migrations位置
  • 验证字段
  • 自定义验证函数
  • 问题: 将model写在不同文件及文件夹下, 无法生成数据表

这有帮助吗?

  1. Coding
  2. Python
  3. Django
  4. DjangoDocs

models

文档版本

Documentation version: 1.10

简单实例

定义

from django.db import models

class Fruit(models.Model):
    name = models.CharField(max_length=100, primary_key=True)

使用

>>> fruit = Fruit.objects.create(name='Apple')
>>> fruit.name = 'Pear'
>>> fruit.save()
>>> Fruit.objects.values_list('name', flat=True)
['Apple', 'Pear']

主键

id = models.AutoField(primary_key=True)

获取所有项

Fruit.objects.clear()

删除所有

Fruit.objects.all().delete()

关系(Relationships)

多对一关系(Many-to-one relationships)

  • 使用django.db.models.ForeignKey定义多对一关系

示例

一辆车(Car)对应多个制造商(Manufacturer )

from django.db import models

class Manufacturer(models.Model):
    # ...
    pass

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
    # ...
  • 定义递归关联(对象关联自身)

    # 定义递归关联
    models.ForeignKey('self', on_delete=models.CASCADE)
  • 使用未定义的Model

    from django.db import models
    
    class Car(models.Model):
        manufacturer = models.ForeignKey(
            # Manufacturer模型还未定义, 可以在这里使用模型名称加上引号代替
            'Manufacturer',
            on_delete=models.CASCADE,
        )
        # ...
    
    class Manufacturer(models.Model):
        # ...
        pass
  • 建议使用模型名称单数形式作为成员变量(如上例中的变量manufacturer)

多对多关系(Many-to-many relationships)

  • 使用ManyToManyField定义多对多关系

判断存不存在

if _book in _booklist.books.all():
    print("书籍已存在")

添加

_booklist.books.add(_book)

示例

一个Pizza(披萨)有多个Topping(配料), 一个Topping可以在多个Pizza上.

from django.db import models

class Topping(models.Model):
    # ...
    pass

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)
  • 可以像多对一关系一样定义递归关联和使用未定义模型

  • 建议使用模型名称复数形式作为成员变量(如上例中的变量toppings)

  • 多对多关系只能在两个相关模型中的一个内定义, 在哪一个里面定义无所谓

  • 通常, 多对多字段(ManyToManyField)应该定义在将要被修改的表格中. 上例中, 在Pizza中定义Topping(配料), 因为相比认为配料在多个披萨里面, 披萨里面有多种配料更容易理解. 按照上例中多对多字段的定义方式, Pizza表可以让用户选择多种配料(而不是配料中选披萨).

    原文:
    Generally, ManyToManyField instances should go in the object that’s going to be edited on a form. In the above example, toppings is in Pizza (rather than Topping having a pizzas ManyToManyField ) because it’s more natural to think about a pizza having toppings than a topping being on multiple pizzas. The way it’s set up above, the Pizza form would let users select the toppings.

另一个示例

文章和出版商.

from django.db import models

class Publication(models.Model):
    title = models.CharField(max_length=30)

    def __str__(self):              # __unicode__ on Python 2
        return self.title

    class Meta:
        ordering = ('title',)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

    class Meta:
        ordering = ('headline',)
  • 注意: 如果使用模型中间件来定义多对多关系, 可能会禁用一些相关的管理方法, 以至于下面的示例可能无法工作

  • 创建几个Publications

    >>> p1 = Publication(title='The Python Journal')
    >>> p1.save()
    >>> p2 = Publication(title='Science News')
    >>> p2.save()
    >>> p3 = Publication(title='Science Weekly')
    >>> p3.save()
  • 创建一个Article

    >>> a1 = Article(headline='Django lets you build Web apps easily')
  • 与保存之前无法和Publication关联

    >>> a1.publications.add(p1)
    Traceback (most recent call last):
    ...
    ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.
  • 保存

    >>> a1.save()
  • 添加关联

    >>> a1.publications.add(p1)
  • 重新创建一个Article并和多个Publication关联

    >>> a2 = Article(headline='NASA uses Python')
    >>> a2.save()
    >>> a2.publications.add(p1, p2)
    >>> a2.publications.add(p3)
  • 重复添加也没问题

    >>> a2.publications.add(p3)
  • 如果添加的对象类型不正确, 会抛出TypeError异常

    >>> a2.publications.add(a1)
    Traceback (most recent call last):
    ...
    TypeError: 'Publication' instance expected
  • 一步完成创建Article并添加Publication

    >>> new_publication = a2.publications.create(title='Highlights for Children')
  • Article对象可以访问相关联的Publication

    >>> a1.publications.all()
    <QuerySet [<Publication: The Python Journal>]>
    >>> a2.publications.all()
    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
  • Publication对象也可以访问相关联的Article对象

    >>> p2.article_set.all()
    <QuerySet [<Article: NASA uses Python>]>
    >>> p1.article_set.all()
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
    >>> Publication.objects.get(id=4).article_set.all()
    <QuerySet [<Article: NASA uses Python>]>
  • 多对多关系可以通过使用跨关系查找(lookups across relationships)查询

    >>> Article.objects.filter(publications__id=1)
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
    >>> Article.objects.filter(publications__pk=1)
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
    >>> Article.objects.filter(publications=1)
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
    >>> Article.objects.filter(publications=p1)
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
    
    >>> Article.objects.filter(publications__title__startswith="Science")
    <QuerySet [<Article: NASA uses Python>, <Article: NASA uses Python>]>
    
    >>> Article.objects.filter(publications__title__startswith="Science").distinct()
    <QuerySet [<Article: NASA uses Python>]>
  • count()和distinct()方法

    >>> Article.objects.filter(publications__title__startswith="Science").count()
    2
    
    >>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
    1
    
    >>> Article.objects.filter(publications__in=[1,2]).distinct()
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
    >>> Article.objects.filter(publications__in=[p1,p2]).distinct()
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>
  • 支持反向多对多查询

    >>> Publication.objects.filter(id=1)
    <QuerySet [<Publication: The Python Journal>]>
    >>> Publication.objects.filter(pk=1)
    <QuerySet [<Publication: The Python Journal>]>
    
    >>> Publication.objects.filter(article__headline__startswith="NASA")
    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
    
    >>> Publication.objects.filter(article__id=1)
    <QuerySet [<Publication: The Python Journal>]>
    >>> Publication.objects.filter(article__pk=1)
    <QuerySet [<Publication: The Python Journal>]>
    >>> Publication.objects.filter(article=1)
    <QuerySet [<Publication: The Python Journal>]>
    >>> Publication.objects.filter(article=a1)
    <QuerySet [<Publication: The Python Journal>]>
    
    >>> Publication.objects.filter(article__in=[1,2]).distinct()
    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
    >>> Publication.objects.filter(article__in=[a1,a2]).distinct()
    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>
  • 执行一个关联工作是非常简单的

    >>> Article.objects.exclude(publications=p2)
    <QuerySet [<Article: Django lets you build Web apps easily>]>
  • 如果我们删除了一个Publication, 它关联的Articles将不能再访问它

    >>> p1.delete()
    >>> Publication.objects.all()
    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]>
    >>> a1 = Article.objects.get(pk=1)
    >>> a1.publications.all()
    <QuerySet []>
  • 如果我们删除了一个Article, 它关联的Publications将不能再访问它

    >>> a2.delete()
    >>> Article.objects.all()
    <QuerySet [<Article: Django lets you build Web apps easily>]>
    >>> p2.article_set.all()
    <QuerySet []>
  • 添加关系

    >>> a4 = Article(headline='NASA finds intelligent life on Earth')
    >>> a4.save()
    >>> p2.article_set.add(a4)
    >>> p2.article_set.all()
    <QuerySet [<Article: NASA finds intelligent life on Earth>]>
    >>> a4.publications.all()
    <QuerySet [<Publication: Science News>]>
    >>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
    >>> p2.article_set.all()
    <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
    >>> a5 = p2.article_set.all()[1]
    >>> a5.publications.all()
    <QuerySet [<Publication: Science News>]>
  • 从Publication中移除Article

    >>> a4.publications.remove(p2)
    >>> p2.article_set.all()
    <QuerySet [<Article: Oxygen-free diet works wonders>]>
    >>> a4.publications.all()
    <QuerySet []>

    也可以通过在Article中移除Publication

    >>> p2.article_set.remove(a5)
    >>> p2.article_set.all()
    <QuerySet []>
    >>> a5.publications.all()
    <QuerySet []>
  • 关系集合可以被设置

    >>> a4.publications.all()
    <QuerySet [<Publication: Science News>]>
    >>> a4.publications.set([p3])
    >>> a4.publications.all()
    <QuerySet [<Publication: Science Weekly>]>
  • 关系集合可以被清空

    >>> p2.article_set.clear()
    >>> p2.article_set.all()
    <QuerySet []>

    或者从关联的对象清空:

    >>> p2.article_set.add(a4, a5)
    >>> p2.article_set.all()
    <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>
    >>> a4.publications.all()
    <QuerySet [<Publication: Science News>, <Publication: Science Weekly>]>
    >>> a4.publications.clear()
    >>> a4.publications.all()
    <QuerySet []>
    >>> p2.article_set.all()
    <QuerySet [<Article: Oxygen-free diet works wonders>]>
  • 批量删除Publications

    >>> Publication.objects.filter(title__startswith='Science').delete()
    >>> Publication.objects.all()
    <QuerySet [<Publication: Highlights for Children>, <Publication: The Python Journal>]>
    >>> Article.objects.all()
    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA finds intelligent life on Earth>, <Article: NASA uses Python>, <Article: Oxygen-free diet works wonders>]>
    >>> a2.publications.all()
    <QuerySet [<Publication: The Python Journal>]>
  • 批量删除Articles

    >>> q = Article.objects.filter(headline__startswith='Django')
    >>> print(q)
    <QuerySet [<Article: Django lets you build Web apps easily>]>
    >>> q.delete()

    ​

多对多关系额外字段

Migrations

生成变更

python manage.py makemigrations

应用变更

python manage.py migrate

字段

datetimefield

from django.utils import timezone
add_time = models.DateTimeField('添加时间', default=timezone.now)   # 默认当前时间

user migrations位置

/usr/local/lib/python3.5/dist-packages/django/contrib/auth/migrations

验证字段

自定义验证函数

# 在上面的例子中, 如果我们希望每篇article title的开头都是"new", 那么应该怎么做呢? 首先我们需要建立自定义的验证(validator):
# utils/validator.py
    from django.core.exceptions import ValidationError

    def validate_begins(value):
        if not value.startswith(u'new'):
            raise ValidationError(u'Must start with new')
# 可见, 在django中的验证程序就是不符合条件便抛出ValidationError的function, 为了方便重复使用, 我们将它们放在django app utils的validators.py中.
# 接下来, 我们可以在model中加入这些validator, 但为了今后的方便修改和维护, 我们更倾向于加入到ModelForm中:
# myapp/forms.py
    from django import forms

    from utils.validators import validate_begin
    from .models import Article

    class ArticleForm(forms.ModelForm):
        dev __init__(self, *args, **kwargs):
            super(ArticleForm, self).__init__(8args, **kwargs)
            self.fields["title"].validators.append(validate_begin)

    class Meta:
        model = Article
# Django的edit views(UpdateView和CreateView等)的默认行为是根据view中model属性, 自动创建ModelForm. 因此, 我们需要调用我们自己的Modelform来覆盖自动创建的:
# myapp/views.py
    from django.views.generic import CreateView, UpdateView

    from braces.views import LoginRequiredMixin

    from .models import Article
    from .forms import ArticleForm

    class ArticleCreateView(LoginRequiredMixin, CreateView):
        model = Article
        fields = ('title', 'slug', 'review_num')
        form_class = ArticleForm

    class ArticleUpdateView(LoginRequiredMixin, UpdateView):
        model = Article
        fields = ('title', 'slug', 'review_num')
        form_class = ArticleForm

问题: 将model写在不同文件及文件夹下, 无法生成数据表

Django会搜索所有继承django.db.models.Model的类, 并生成相应的数据表,如果没能正常生成, 可能的原因:

  • 定义model的源文件的路径中有文件夹下不包含__init__.py, 这样python不会把该文件夹当作package

上一页设置media路径下一页manage.py使用

最后更新于4年前

这有帮助吗?

参考一