Django文档翻译:模型参考(Model Reference)

Django文档翻译:模型参考(Model Reference)
翻译者: 木野狐(Neil Chen)
Django 版本: 0.95.1
进度: 未完,持续更新中。
最后更新时间: 2007-2-22

 


body,table,td,p,.pre {font-size:9pt; font-family:Arial, Helvetica, sans-serif;} .pre{font-family:"Courier New", Courier, mono; color:navy;} .tran_cn{color:#FF9900; font-weight:bold;} .code{background-color:#CCCCCC; font-size:9pt; font-family:"Courier New", Courier, mono;} .comment{color:#009900;} /* :Author: David Goodger :Contact: goodger@python.org :Date: $Date: 2006-05-21 22:44:42 +0200 (Sun, 21 May 2006) $ :Revision: $Revision: 4564 $ :Copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to customize this style sheet. */ /* used to remove borders from tables and images */ .borderless, table.borderless td, table.borderless th { border: 0 } table.borderless td, table.borderless th { /* Override padding for "table.docutils td" with "! important". The right padding separates the table cells. */ padding: 0 0.5em 0 0 ! important } .first { /* Override more specific margin styles with "! important". */ margin-top: 0 ! important } .last, .with-subtitle { margin-bottom: 0 ! important } .hidden { display: none } a.toc-backref { text-decoration: none ; color: black } blockquote.epigraph { margin: 2em 5em ; } dl.docutils dd { margin-bottom: 0.5em } /* Uncomment (and remove this text!) to get bold-faced definition list terms dl.docutils dt { font-weight: bold } */ div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.admonition, div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.admonition p.admonition-title, div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } /* Uncomment (and remove this text!) to get reduced vertical space in compound paragraphs. div.compound .compound-first, div.compound .compound-middle { margin-bottom: 0.5em } div.compound .compound-last, div.compound .compound-middle { margin-top: 0.5em } */ div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em ; margin-right: 2em } div.footer, div.header { clear: both; font-size: smaller } div.line-block { display: block ; margin-top: 1em ; margin-bottom: 1em } div.line-block div.line-block { margin-top: 0 ; margin-bottom: 0 ; margin-left: 1.5em } div.sidebar { margin-left: 1em ; border: medium outset ; padding: 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.section-subtitle, h2.section-subtitle, h3.section-subtitle, h4.section-subtitle, h5.section-subtitle, h6.section-subtitle { margin-top: 0.4em } h1.title { text-align: center } h2.subtitle { text-align: center } hr.docutils { width: 75% } img.align-left { clear: left } img.align-right { clear: right } ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font-family: serif ; font-size: 100% } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.pre { white-space: pre } span.problematic { color: red } span.section-subtitle { /* font-size relative to parent (h1..h6 element) */ font-size: 80% } table.citation { border-left: solid 1px gray; margin-left: 1px } table.docinfo { margin: 2em 4em } table.docutils { margin-top: 0.5em ; margin-bottom: 0.5em } table.footnote { border-left: solid 1px black; margin-left: 1px } table.docutils td, table.docutils th, table.docinfo td, table.docinfo th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } table.docutils th.field-name, table.docinfo th.docinfo-name { font-weight: bold ; text-align: left ; white-space: nowrap ; padding-left: 0 } h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { font-size: 100% } ul.auto-toc { list-style-type: none }

Model reference
模型参考

A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table.

The basics:

  • Each model is a Python class that subclasses django.db.models.Model.
  • Each attribute of the model represents a database field.
  • Model metadata (non-field information) goes in an inner class named Meta.
  • Metadata used for Django's admin site goes into an inner class named Admin.
  • With all of this, Django gives you an automatically-generated database-access API, which is explained in the Database API reference.

A companion to this document is the official repository of model examples. (In the Django source distribution, these examples are in the tests/modeltests directory.)

Quick example

This example model defines a Person, which has a first_name and last_name:

from django.db import models

class Person(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)

first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.

The above Person model would create a database table like this:

CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);

Some technical notes:

  • The name of the table, myapp_person, is automatically derived from some model metadata but can be overridden. See Table names below.
    表名 myapp_person 从模型的元数据自动产生,但也可以被重写。
  • An id field is added automatically, but this behavior can be overriden. See Automatic primary key fields below.
    id 字段是自动附加的,也可以被重写。
  • The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it's worth noting Django uses SQL tailored to the database backend specified in your settings file.

Fields

The most important part of a model -- and the only required part of a model -- is the list of database fields it defines. Fields are specified by class attributes.

Example:


class Musician(models.Model):
first_name = models.CharField(maxlength=50)
last_name = models.CharField(maxlength=50)
instrument = models.CharField(maxlength=100)


class Album(models.Model):
artist = models.ForeignKey(Musician)
# 定义外键
name = models.CharField(maxlength=100)
release_date = models.DateField()
# 日期字段
num_stars = models.IntegerField()

Field name restrictions

Django places only two restrictions on model field names:

  1. A field name cannot be a Python reserved word, because that would result in a Python syntax error. For example:
    字段名不能是 Python 保留字

    class Example(models.Model):
    pass = models.IntegerField() # 'pass' is a reserved word!
  2. A field name cannot contain more than one underscore in a row, due to the way Django's query lookup syntax works. For example:
    字段名不能包含多于一个下划线。因为 Django 的 query 查找语法。

    class Example(models.Model):
    foo__bar = models.IntegerField() 'foo__bar' has two underscores!

These limitations can be worked around, though, because your field name doesn't necessarily have to match your database column name. See db_column below.

SQL reserved words, such as join, where or select, are allowed as model field names, because Django escapes all database table names and column names in every underlying SQL query. It uses the quoting syntax of your particular database engine.
SQL 保留字,如 join, where, select,可以被用作模型的字段名。

Field types

Each field in your model should be an instance of the appropriate Field class. Django uses the field class types to determine a few things:

  • The database column type (e.g. INTEGER, VARCHAR).
  • The widget to use in Django's admin interface, if you care to use it (e.g. type="text">, box with "Unknown", "Yes" and "No" choices.

PhoneNumberField
电话号码字段

A CharField that checks that the value is a valid U.S.A.-style phone number (in the format XXX-XXX-XXXX).
表示美国电话号码的格式的字段(xxx-xxx-xxxx)

PositiveIntegerField
正整数字段

Like an IntegerField, but must be positive.

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.
"Slug" 是报纸的术语。表示一个短的标签,仅包含字母,数字,下划线或连字符。一般用于 URL 中。

In the Django development version, you can specify maxlength. If maxlength is not specified, Django will use a default length of 50. In previous Django versions, there's no way to override the length of 50.
在 Django 开发版中,可指定 maxlength. 默认的长度是 50. 在低版本的 Django 中,没有办法可以覆盖长度为 50 的限制。

Implies db_index=True.
隐含 db_index=True

Accepts an extra option, prepopulate_from, which is a list of fields from which to auto-populate the slug, via JavaScript, in the object's admin form:
接受一个额外选项 prepopulate_from,用于指示在 admin 表单中的可选值。

models.SlugField(prepopulate_from=("pre_name", "name"))

prepopulate_from doesn't accept DateTimeFields.
prepopulate_from 不接受 DateTimeField 字段

The admin represents SlugField as an type="text"> (a single-line input).

SmallIntegerField
小整数字段

Like an IntegerField, but only allows values under a certain (database-dependent) point.

TextField
大文本字段

A large text field.

The admin represents this as a