标签:tar with remove rem from 检索 adl http contain
昨天晚上,我们完成了一个简单的实例来对数据库表进行操作。今天,我们要熟悉更多的API,实现更复杂的功能。这一步完成了,我们对小型数据的操作问题也就不大了。
现在,我们还是参考django官方文档,来进行学习
把以下内容,拷贝到你的朋友charm中,然后执行migrate命令
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
b.save()
这样,我们就把数据存进去了
同一个对象,保存之后重新赋值,就会执行修改操作
3.保存 ForeignKey 和 ManyToManyField 字段
现在,我们数据已经保存了,并已经建立了关联
在model中,Entry关联了外键Blog(ForeignKey )
所以在创建Entry的时候,要先获取一个Blog对象,给Entry赋值之后,才执行保存数据库的操作
entry = Entry(headline=‘test123‘, body_text=‘test123‘, pub_date=datetime.datetime.now(),
mod_date=datetime.datetime.now(), n_comments=123, n_pingbacks=456, rating=789)
cheese_blog = Blog.objects.get(name="Beatles Blog")
entry.blog = cheese_blog
entry.save()
现在处理ManyToManyField 的情况
存进去了,还得能取出来:
data = entry.authors.iterator()
直接访问属性,并把查询集转为可迭代
all_entries = Entry.objects.all()
filter(**kwargs) 返回一个新的匹配查询参数后的QuerySet
exclude(**kwargs) 返回一个新的不匹配查询参数后的QuerySet
Entry.objects.filter(pub_date__year=2006)
q2 = q1.exclude(pub_date__gte=datetime.date.today())
Entry.objects.filter(headline__startswith=‘What‘)
.exclude(pub_date__gte=datetime.now())
.filter(pub_date__gte=datetime(2005, 1, 1))
创建QuerySets不会触及到数据库操作,你可以多个过滤合并到一起,直到求值的时候django才会开始查询
q = Entry.objects.filter(headline__startswith="What")
q = q.filter(pub_date__lte=datetime.now())
q = q.exclude(body_text__icontains="food")
one_entry = Entry.objects.get(pk=1)
Entry.objects.all()[:5]
Entry.objects.order_by(‘headline‘)[0:1].get()
Entry.objects.filter(pub_date__lte=‘2006-01-01‘)
转换成SQL:
SELECT * FROM blog_entry WHERE pub_date <= ‘2006-01-01‘;
Entry.objects.get(headline__exact="Man bites dog")
转换成SQL:
SELECT ... WHERE headline = ‘Man bites dog‘;
Blog.objects.get(name__iexact="beatles blog")
Entry.objects.get(headline__contains=‘Lennon‘)
转换成SQL:
SELECT ... WHERE headline LIKE ‘%Lennon%‘;
icontains 不区分大小写
startswith,endswith,istartswith,iendswith
前后模糊查询
查询blog__name匹配的,返回Entry
Entry.objects.filter(blog__name__exact=‘Beatles Blog‘)
查询entry__headline匹配的,返回Blog
Blog.objects.filter(entry__headline__contains=‘Lennon‘)
如果跨越多层关系查询,中间模型没有值,django会作为空对待不会发生异常
Blog.objects.filter(entry__author__name=‘Lennon‘);
Blog.objects.filter(entry__author__name__isnull=True);
Blog.objects.filter(
entry__author__isnull=False,
entry__author__name__isnull=True);
from django.db.models import F
Entry.objects.filter(n_pingbacks__lt=F(‘n_comments‘))
列加减乘除都可以
Entry.objects.filter(n_pingbacks__lt=F(‘n_comments‘) * 2)
Entry.objects.filter(rating__lt=F(‘n_comments‘) + F(‘n_pingbacks‘))
Entry.objects.filter(author__name=F(‘blog__name‘))
Entry.objects.filter(headline__contains=‘%‘)
转义为:
SELECT ... WHERE headline LIKE ‘%\%%‘;
q = Entry.objects.filter(headline__startswith="What")
q.delete()
Entry.objects.filter(pub_date__year=2007).update(headline=‘Everything is the same‘)
一次性修改所有的Entry的blog属性指向
b = Blog.objects.get(pk=1)
Entry.objects.all().update(blog=b)
update也可以使用F()
Entry.objects.update(headline=F(‘blog__name‘))
e = Entry.objects.get(id=2)
print e.blog # Hits the database to retrieve the associated Blog
e = Entry.objects.select_related().get(id=2)
print e.blog # 不会在向数据库取; 使用缓存中的值.
b = Blog.objects.get(id=1)
b.entry_set.all() # 返回所有blog的关联对象.
# b.entry_set is a Manager that returns QuerySets.
b.entry_set.filter(headline__contains=‘Lennon‘)
b.entry_set.count()
b = Blog.objects.get(id=1)
b.entries.all() # 返回所有blog的关联对象
# b.entries is a Manager that returns QuerySets.
b.entries.filter(headline__contains=‘Lennon‘)
b.entries.count()
add(obj1, obj2, ...) 把多个对象建立连接
create(**kwargs) 建立新对象
remove(obj1, obj2, ...) 移除多个关系对象
clear() 清理所有关系对象
20.Many-to-many关系
e = Entry.objects.get(id=3)
e.authors.all() # 返回Entry所有authors
e.authors.count()
e.authors.filter(name__contains=‘John‘)
a = Author.objects.get(id=5)
a.entry_set.all() # 返回Author所有entry
21.One-to-one关系
要在定义模型的时候设置
class EntryDetail(models.Model):
entry = models.OneToOneField(Entry)
details = models.TextField()
ed = EntryDetail.objects.get(id=2)
ed.entry # 返回 Entry 对象.
标签:tar with remove rem from 检索 adl http contain
原文地址:http://www.cnblogs.com/zijiyanxi/p/7599075.html