Django 模型

连接数据库:
from django.shortcuts import render_to_response
import MySQLdb

def book_list(request):
db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT name FROM books ORDER BY name')
names = [row[0] for row in cursor.fetchall()]
db.close()
return render_to_response('book_list.html', {'names': names})

setting.py数据库设置:


image.png

image.png

image.png

model模型:


image.png

验证模型语法:


image.png

生成数据库:python manage.py sqlall books

模型:
from django.db import models

class Publisher(models.Model):
name = models.CharField(max_length=30)
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 Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()

**def __unicode__(self):**
    **return u'%s %s' % (self.first_name, self.last_name)**

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

**def __unicode__(self):**
    **return self.title**

过滤:

Publisher.objects.filter(name='Apress')
[]
Publisher.objects.filter(country="U.S.A.", state_province="CA")
[]
获取单个对象:
Publisher.objects.get(name="Apress")

捕获异常:
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.order_by("name")
[, ]
Publisher.objects.order_by("state_province", "address")
[, ]
Publisher.objects.order_by("-name")
[, ]

缺省排序:
class Publisher(models.Model):
name = models.CharField(max_length=30)
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 Meta:**
    **ordering = ['name']**

链式:

Publisher.objects.filter(country="U.S.A.").order_by("-name")
[, ]

列表

Publisher.objects.order_by('name')[0]

特定
Publisher.objects.order_by('name')[0:2]
更新:
p = Publisher.objects.get(name='Apress')
p.name = 'Apress Publishing'
p.save()

更新:

Publisher.objects.filter(id=52).update(name='Apress Publishing')

删除:

p = Publisher.objects.get(name="O'Reilly")
p.delete()
Publisher.objects.all()
[]

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

你可能感兴趣的:(Django 模型)