1. 程式人生 > >Django templates and models

Django templates and models

改變 lar 情況 repr 返回 tps created ould sage

  • 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)
View Code

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
);
View Code

註意:表名是 ---應用名字_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,
]
View Code

books 是我的app name, BooksConfig 是apps.py 文件中定義的類名

使用以下兩條命令

技術分享
python manage.py makemigrations

python manage.py migrate
View Code

執行第一條命令後你會在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()
View Code

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 is False.
  • primary key 如果是True ,指定這個字段是主鍵
  • unique 如果是True 這個字段數據唯一的,不能重復

關於field name 的約束

django 對於field name 只有兩個約束

  1. 不能是Python的保留字,比如pass for try 等,否則會出現語法錯誤
  2. 字段名字不能包含超過1個下劃線 (_) 這是由於django 的查詢語法的工作模式導致的
技術分享
class Example(models.Model):
    foo__bar = models.IntegerField() 
# ‘foo__bar‘ has two underscores!
View Code

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
View Code
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 QuerySetcontaining a single element.

使用get()會返回一個object

你就可以直接使用它

Django templates and models