实用型的DJANGO ORM
比较深入一点的内容,需要用时,用心看看。
URL:
https://www.sitepoint.com/doing-more-with-your-django-models/
https://www.sitepoint.com/doing-more-with-your-django-models/
So you have a Django app, but sometimes you find the Django models too constraining. We will guide you through using Django models to get more out of them. This is an intermediate tutorial, as some familiarity with Django is assumed. For example, we assume you know how to write a basic Django model, you know how to override Python methods, as well as how .filter and .exclude work.
We will talk about these topics
- Proxy Models
- Overriding
.save - Using signals
- Optimizing your DB access using
.extra - Advanced lookups using Q objects
- Aggregation and Annotation
- Using F() expressions
Lets look at some common operations you may want to perform using Django and how the above Django functionality will help you achieve them.
How can I get two Python representation of the same Database table?
You may want to have two model classes corresponding to a single database table. For example,admin.site.register allows a Model to be registered only once. However, you may want the same model twice in the Admin area. Proxy models can help you do that!
from django.contrib.auth.models import User
class NewUser(User):
class Meta:
proxy = True
Now in your admin.py you can register NewUser again and customize your ModelAdmin. (For example, if you want to show only some of the fields, add a custom ordering and so on).
How can I take action before saving a model to database?
Sometime you may have some denormalized data. Consider this model:
class Poll(models.Model):
###...
num_choices = models.PositiveIntegerField()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
###...
You want to increment the num_choices before saving Choice. You can do that by overriding .save like this.
def save(self, *args, **kwargs):
self.poll.num_choices += 1
self.poll.save()
super(Choice, self).save(*args, **kwargs)
How can I take action before saving the models to database if I didn’t write the model?
Overriding .save is great when you are writing all the models. However for example you have aSubscription model and when someone sings up they are assigned a subscription. However since you didn’t write the User model, you can not override the .save model.
Django emits signals before taking any action. You can connect your functions to signals to take action when interesting stuff happens. Django comes with two signalspre_save and post_save which you can connect to.
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
def subscription_handler(**kwargs):
#Do something with the Subscription model
pre_save.connect(subscription_handler, sender=User, dispatch_uid="subscription_handler")
How can I get related objects without hitting the database many times?
Assume we have these models:
class Subject(models.Model):
###...
class Score(models.Model):
###...
subject = models.ForeignKey(Subject)
score = models.PositiveIntegerField()
Now you are iterating over a Subject queryset, and you want the sum of all the Score objects which have a foreign key to current object. You can do this by getting individual Score objects and then summing them in Python, but it would be faster to do that in the database. Django has a method .extra which allows you to insert arbitrary clauses in the sql generated by the queryset. For example here you can do
Subject.objects.extra(select={"total_scores": "select sum(score) from poll_score where poll_score.subject_id = poll_subject.id"})
assuming that the app is called poll for which the default names for tables are poll_subject andpoll_score.
How can you compose OR, NOT and other SQL operations?
By default Django will AND all criteria passed to the filtering methods. If you want to use OR/NOT operator, you will need to use Q objects.
We have a model like:
class Score(models.Model):
###...
subject = models.ForeignKey(Subject)
score = models.PositiveIntegerField()
date = models.DateField()
So, if you want all Score objects for Physics which have either score > 95 or are in 2012.
criteria = Q(subject__name="Physics") & (Q(score__gt=95)|Q(date__year=2012))
We used the double underscore notation to apply filters and joined them together using boolean operators. You can pass them to .filter. (Or to .exclude)
Score.objects.filter(criteria)
How can I get group_by type of operations?
Django provides two methods on its querysets – .aggregate and .annotate. Aggregates convert the queryset in a dictionary on name, value pairs.
E.g., if you want the maximum, minimum, and average of Score objects. You can get them as
from django.db.models import Avg, Max, Min
Score.objects.all().aggregate(Max('score'), Avg('score'), Min('score'))
For more, see the guide on aggregation
How can I compare within rows?
Django provides F objects which are used to create queries which compare within rows.
We have a model like this:
class Department(models.Model):
##...
num_employees = models.PositiveIntegerField()
num_managers = models.PositiveIntegerField()
You want to find all departments which have more managers than employees.
from django.db.models import F
Department.objects.filter(num_managers__gt=F('num_employees'))
F objects support addition, subtraction, multiplication, division so you can do things like
Department.objects.filter(num_employees__lt=F('num_managers')*2)
实用型的DJANGO ORM的更多相关文章
- django orm总结[转载]
django orm总结[转载] 转载地址: http://www.cnblogs.com/linjiqin/archive/2014/07/01/3817954.html 目录1.1.1 生成查询1 ...
- Django ORM - 001 - 外键表查询主表信息
开始用Django做web开发,我想大家都会遇到同样的问题,那就是如何高效快速的查询需要的数据,MVC都很简单,但是ORM折腾起来就有些费时间,我准备好好研究下Django ORM,所以会有一个系列的 ...
- Django ORM 中的批量操作
Django ORM 中的批量操作 在Hibenate中,通过批量提交SQL操作,部分地实现了数据库的批量操作.但在Django的ORM中的批量操作却要完美得多,真是一个惊喜. 数据模型定义 首先,定 ...
- Django ORM 查询管理器
Django ORM 查询管理器 ORM 查询管理器 对于 ORM 定义: 对象关系映射, Object Relational Mapping, ORM, 是一种程序设计技术,用于实现面向对象编程语言 ...
- Django ORM模型的一点体会
作者:Vamei 出处:http://www.cnblogs.com/vamei 严禁转载. 使用Python的Django模型的话,一般都会用它自带的ORM(Object-relational ma ...
- 数据库表反向生成(二) Django ORM inspectdb
在前一篇我们说了,mybatis-generator反向生成代码. 这里我们开始说如何在django中反向生成mysql model代码. 我们在展示django ORM反向生成之前,我们先说一下怎么 ...
- Django ORM那些相关操作
一般操作 https://docs.djangoproject.com/en/1.11/ref/models/querysets/ 官网文档 常用的操作 <1> all() ...
- django orm 及常用参数
一些说明: 表myapp_person的名称是自动生成的,如果你要自定义表名,需要在model的Meta类中指定 db_table 参数,强烈建议使用小写表名,特别是使用MySQL作为后端数据库时. ...
- Django ORM中,如何使用Count来关联对象的子集数量
示例models 解决方法 有时候,我们想要获取一个对象关联关系的数量,但是我们不要所有的关联对象,我们只想要符合规则的那些关联对象的数量. 示例models # models.py from dja ...
随机推荐
- ACM_Fibonacci数(同余)
Fibonacci数 Time Limit: 2000/1000ms (Java/Others) Problem Description: 斐波那契数列定义如下:f(0)=0,f(1)=1,f(n+2 ...
- docker血一样的教训,生成容器的时候一定要设置数据卷,把数据文件目录,配置文件目录,日志文件目录都要映射到宿主机上保存啊!!!
打个比方,比如mysql,如果你想重新设置一下mysql的配置,不小心配错里,启动容器失败,已启动就停止了. 根本进不去mysql的容器里.如果之前run容器的时候,没有把数据文件,日志文件,配置文件 ...
- Android 性能优化(4)Optimizing Layout Hierarchies:用Hierarchy Viewer和Layoutopt优化布局
Optimizing Layout Hierarchies This lesson teaches you to Inspect Your Layout Revise Your Layout Use ...
- 406 Queue Reconstruction by Height 根据身高重建队列
假设有打乱顺序的一群人站成一个队列. 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数. 编写一个算法来重建这个队列.注意:总人数少于1100人.示 ...
- 235 Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先
给定一棵二叉搜索树, 找到该树中两个指定节点的最近公共祖先. 详见:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-s ...
- .Net实战之反射外卖计费
场景 叫外卖支付,可以有以下优惠: 1. 满30元减12 2. 是会员减配送费,比如5元 3. 优惠券 …. 问题? 如何在不改代码的情况下更灵活的去控制优惠的变化??? 有些代码与实际业务可能 ...
- Elasticsearch--地理搜索
目录 地理位置索引 空间搜索映射定义 示例 基于距离的排序 边界框过滤 距离的限制 任意地理形状搜索 点 包络线 多边形 多个多边形 把形状保存到索引中 地理位置索引 空间搜索映射定义 elastic ...
- springboot运行模式
1.springboot项目常见的运行方式: 2.说明: idea:在开发环境中跑项目,也就是我们在编码过程中的用的做多的方式 jar.war:线上.服务器上执行jar.war包的方式 maven插 ...
- python自动化--语言基础四模块、文件读写、异常
模块1.什么是模块?可以理解为一个py文件其实就是一个模块.比如xiami.py就是一个模块,想引入使用就在代码里写import xiami即可2.模块首先从当前目录查询,如果没有再按path顺序逐一 ...
- 简述 MVC, MVP, MVVM三种模式
Make everything as simple as possible, but not simpler - Albert Einstein* 把每件事,做简单到极致,但又不过于简单 - 阿尔伯特 ...