django基础 --- 模型

2016-12-12  本文已影响0人  梦想做小猿

配置

一: 新建app

python manage.py startapp books

二:setting.py添加app

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books', #添加的app
)

三:连接mysql配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mysite',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

四:编辑models

from django.db import models

#出版社信息表
class Publisher(models.Model):
    name = models.CharField(max_length=20)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

    def __unicode__(self):
        return self.name

#作者表
class Auther(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __unicode__(self):
        return"%s %s"%(self.first_name,self.last_name)

#书籍表
class Books(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Auther)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.title

解释:
_unicode方法:用来以字符串来显示查询的时候所查询到的数据,如果不加则全显示为object无法知道是哪一条数据,Python版本为3.*使用_str

五:将表结构写入数据库

python manage.py makemigrations
python manage.py migrate

使用

进入django shell命令行

python manage.py shell
>>> from books.models import *
p1 = Publisher.objects.create(name='Apress', address='2855 Telegraph Avenue',city='Berkeley', state_province='CA', country='U.S.A.',website='http://www.apress.com/')
p2 = ....
Publisher.objects.all()

2.过滤查询

#select xxx,xxx from Publisher where city="Berkeley"
Publisher.objects.filter(city="Berkeley")
#select xxx,xxx from Publisher where city="Berkeley" and name="Apress"
Publisher.objects.filter(city="Berkeley",name="Apress")

python =是精确匹配,要实现like语句则使用__contains

#select xxx,xxx from Publisher where name like "%press%"
Publisher.objects.filter(name__contains="press")

3.排序查询
正向排序

Publisher.objects.order_by("name")
#或
Publisher.objects.order_by("name","city")
#第二个参数会在第一个相同的情况下被使用

逆向排序(参数前面加一个减号即可)

Publisher.objects.order_by("-name")

4.查询指定字段
values:

Publisher.objects.values("name")
#返回列表内嵌字典
[{"name":"Apress"},{"name":"..."},....]

values_list:

Publisher.objects.values_list("name")
#返回列表内嵌元祖
[("Apress"),("..."),...]
Publisher.objects.get(name="Apress")

注:如果获取单个为空会触发DoesNotExist 异常,需要用try处理:

try:
    p = Publisher.objects.get(name='Apress')
except Publisher.DoesNotExist:
    print "Apress isn't in the database yet."
else:
    print "Apress is in the database."
Publisher.objects.filter(id=1).update(name='Apress Publishing')

改多个

Publisher.objects.all().update(country='USA')

注:django修改数据,先查询要改的数据,然后update

Publisher.objects.filter(country='USA').delete()

注:删除数据和更新数据一样,先查询后delete

上一篇下一篇

猜你喜欢

热点阅读