Django templates and models
Posted dragonbird
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django templates and models相关的知识,希望对你有一定的参考价值。
-
models
-
templates
models
如何理解models
A model is the single, definitive source of information 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.
- With all of this, Django gives you an automatically-generated database-access API; see Making queries.
quick example
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
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 );
注意:表名是 ---应用名字_class名字 ,你可以重写他们
ID字段是自动添加的,并设置为主键,当然你也可以重写他们
要想使写的model在数据库生效,你需要在 INSTALLED_APPS中添加进你的应用,像这样
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘books.apps.BooksConfig‘, ]
books 是我的app name, BooksConfig 是apps.py 文件中定义的类名
使用以下两条命令
python manage.py makemigrations
python manage.py migrate
执行第一条命令后你会在migrations文件夹中看到0001_initial.py文件
manage.py migrate 这条命令是迁移到数据库,数据库中会有你创建的表
Fileds(字段)
数据表中的字段被class attributes 所指定。需要注意的是,字段的名字不要和model API 冲突,like clear delete save
example
from django.db import models class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField()
field options
以下是字段常用的参数
- null 如果是True, django会将空值存储为null在数据库中,默认是False
- 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.
- choice An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. If this is given,the default form widget will be a select box instead of the standard text field and will limit choices to the choices given.
- blank(空白) If
True
, the field is allowed to be blank. Default isFalse
. - primary key 如果是True ,指定这个字段是主键
- unique 如果是True 这个字段数据唯一的,不能重复
关于field name 的约束
django 对于field name 只有两个约束
- 不能是Python的保留字,比如pass for try 等,否则会出现语法错误
- 字段名字不能包含超过1个下划线 (_) 这是由于django 的查询语法的工作模式导致的
class Example(models.Model): foo__bar = models.IntegerField() # ‘foo__bar‘ has two underscores!
making query 查询
一旦你创建了数据模型,django会自动提供数据库抽象API让你创建,更新,删除object
refer to the following models
from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): # __unicode__ on Python 2 return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return self.name class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): # __unicode__ on Python 2 return self.headline
creating object
Django uses an intuitive system:
A model class represents a database table, and an instance of that class represents a particular record in the database table.
模型类代表数据表,这个l类的实例代表这个数据表中一个特定的实例。
>>> from blog.models import Blog >>> b = Blog(name=‘Beatles Blog‘, tagline=‘All the latest Beatles news.‘) name是blog类中的属性,即指定的字段 >>> b.save()
这个行为相当于在幕后执行了INSERT SQL 语句
这是一种插入数据的方式,还有另一种插入数据的方式:
>> Blog.object.create(name="libai",tagline="all the latest beatles news")
这种方式不需要save
Saving changes to objects
使用.save()来保存改变的对象
例如
b.name="李白"
b.save()
retrieving object(检索对象)
To retrieve objects from your database, construct a QuerySet
via a Manager
on your model class.
为了检索从数据库的对象,通过model类的manage方法构建一个QuerySet
关于manage方法,如果不设置名字,默认名字是objects
A QuerySet represents a collection of objects from your database. It can have zero, one or many filters.
QuertSet 代表数据库中对象的集合,他有0个,1个或者多个过滤器 从SQL角度来看,QuerySet相当于select语句,filter相当于where having
You get a QuerySet
by using your model’s Manager
. Each model has at least one Manager
, and it’s called objects
by default. Access it directly via the model class, like so:
NOtes:
实例是没有manage方法的
like:
>>> Blog.objects <django.db.models.manager.Manager object at ...> >>> b = Blog(name=‘Foo‘, tagline=‘Bar‘) >>> b.objects Traceback: ... AttributeError: "Manager isn‘t accessible via Blog instances."
检索所有的objects
all_entries=Entry.objects.all()
很多f情况下我们需要匹配特定的,这时需要用到过滤器
Retrieving specific objects with filters
两种方法:
filter(**kwargs)
Returns a new QuerySet
containing objects that match the given lookup parameters.
excludet(**kwargs)
Returns a new QuerySet
containing objects that do not match the given lookup parameters.
For example, to get a QuerySet
of blog entries from the year 2006, use filter()
like so:
Entry.objects.filter(pub_date__year=2006)
With the default manager class, it is the same as:
Entry.objects.all().filter(pub_date__year=2006)
Retrieving a single object with get()
filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet
containing a single element.
使用get()会返回一个object
你就可以直接使用它
以上是关于Django templates and models的主要内容,如果未能解决你的问题,请参考以下文章
document.compatMode,quirks mode and standards mode