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 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!

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

使用get()会返回一个object

你就可以直接使用它

时间: 2024-08-05 19:30:22

Django templates and models的相关文章

Django Templates

二分春色到穷阎,儿女祈翁出滞淹.幽蛰夜惊雷奋地,小窗朝爽日筛帘. 惠风全解墨池冻,清昼胜翻云笈签.亲友莫嗔情话少,向来屏息似龟蟾. 料峭寒犹薄,阴云带晚烟. 雨催惊蛰候,风作勒花开. 日永消香篆,愁浓逼酒船. 为君借余景,收拾赋新篇. 作者:小亲姐姐来源链接:http://www.qbaobei.com/jiaoyu/407464.html来源:亲亲宝贝著作权归作者所有. 料峭寒犹薄,阴云带晚烟. 雨催惊蛰候,风作勒花开. 日永消香篆,愁浓逼酒船. 为君借余景,收拾赋新篇. 作者:小亲姐姐来源链

django froms与models结合使用

下面介绍forms模块如何与后台数据库交互,把from提交过来的数据写入到后台数据库中 froms与model结合使用 1.vim modes.py中创建数据表 from django.db import models class admin(model.Model): gender_tuple=( (1,'男'), (2,'女'), ) username = models.Char Field(max_length=50) email = models.CharField(max_length

django学习之- Models笔记

1:创建数据库表 #单表# app01_user 生成的表明为 tb1class User(models.Model): name = models.CharField(max_length=32,db_index=True) # 单列创建索引 email = models.CharField(max_length=32) class Meta: # 生成的表名:tb1 #数据库中生成的表名称,默认app名称+下划线+类名 db_table='tb1' (重要) index_together={

13.Django之数据库models&amp;orm连表操作补充以及其他知识点补充(二)

一.外键关联. 假如说,现在有两张表,一张user表,这个表中存放了用户账户信息,还有一张usertype表,这张表存放了用户账户的类型. from django.db import models class UserType(models.Model): #用户类型表,虽然没有创建ID字段,但是ID字段会自动创建. type = models.CharField(max_length=32) class User(models.Model): #用户表 username = models.Ch

django ORM中models的字段以及参数

字段: AutoField(Field)         - int自增列,必须填入参数 primary_key=True     BigAutoField(AutoField)         - bigint自增列,必须填入参数 primary_key=True         注:当model中如果没有自增列,则自动会创建一个列名为id的列         from django.db import models         class UserInfo(models.Model):

Django报错 No module named &#39;django.templates&#39;

前言 Django 模板报错了 修改方法: 将你的工程文件下(my_site)的settings.py中的TEMPLATES中的templates字段全部改为template, 亲测可用~^~ Django报错 No module named 'django.templates' 原文地址:https://www.cnblogs.com/yf-html/p/9314280.html

Django在根据models生成数据库表时报 __init__() missing 1 required positional argument: &#39;on_delete&#39;

code: 1 #encoding=utf-8 2 from django.db import models 3 # Create your models here. 4 class BookInfo(models.Model): #创建书本信息类,继承models.Model 5 booktitle=models.CharField(max_length=20) 6 bookdata=models.DateField() 7 class HeroInfo(models.Model): #创建英

Django 使用allauth报错 RuntimeError: Model class django.contrib.sites.models.Site doesn&#39;t declare an explicit app_label and isn&#39;t in an application in INSTALLED_APPS

一:报错 RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS 出现这种情况需将Django的Sites框架添加到您的应用程序中,并在您的设置中将SITE_ID设置为1即可.位置放在默认配置的后面,其他应用的前面. INSTALLED_APPS = [ 'django

Django在使用models生成数据库表时报错: __init__() missing 1 required positional argument: &#39;on_delete&#39;

Django 提供完善的模型(model)层主要用来创建和存取数据,不需要我们直接对数据库操作.Django 模型基础知识: 1.每个模型是一个 Python 类,继承 django.db.models.model 类. 2.该模型的每个属性表示一个数据库表字段. 程序代码如下: # 创建应用程序数据表模型(对应数据库的相关操作) from django.db import models # 导入models模块 class Event(models.Model): # 创建Event类,继承m