<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<atom:link href="http://itecfun.com/extern.php?action=feed&amp;tid=85&amp;type=rss" rel="self" type="application/rss+xml" />
		<title><![CDATA[个人知识管理站 / django model filter 条件过滤，及多表连接查询、反向查询，某字段的distinct]]></title>
		<link>http://www.itecfun.com/viewtopic.php?id=85</link>
		<description><![CDATA[django model filter 条件过滤，及多表连接查询、反向查询，某字段的distinct 最近发表的帖子。]]></description>
		<lastBuildDate>Thu, 05 Feb 2015 07:46:47 +0000</lastBuildDate>
		<generator>FluxBB</generator>
		<item>
			<title><![CDATA[Re: django model filter 条件过滤，及多表连接查询、反向查询，某字段的distinct]]></title>
			<link>http://www.itecfun.com/viewtopic.php?pid=162#p162</link>
			<description><![CDATA[<p><strong>django 动态查询,动态 增加 filter&#160; 字段</strong></p><br /><p>在用DJANGO开发应用的时候，通常会涉及对多个字段进行查询，并得到结果。<br />但有时候，比如自定义查询时，字段并不是定死的，而是动态增加的。<br />比如有一个类：<br />程序代码 程序代码</p><p>class Entry( models.Model ):<br />&#160; &#160; user = models.CharField(max_length=64)<br />&#160; &#160; category = models.CharField(max_length=64 )<br />&#160; &#160; title = models.CharField( max_length = 64 )<br />&#160; &#160; entry_text = models.TextField()<br />&#160; &#160; deleted_datetime = models.DateTimeField()</p><p>我们的目标是做成一个动态的查询。这个时候需要用到 kwargs.</p><p>程序代码 程序代码</p><p>kwargs = {<br />&#160; &#160; # 动态查询的字段<br />}</p><p># 选择deleted_datetime为空的记录<br />if exclude_deleted:<br />&#160; &#160; kwargs[ &#039;deleted_datetime__isnull&#039; ] = True</p><p># 选择特的category<br />if category is not None:<br />&#160; &#160; kwargs[ &#039;category&#039; ] = category</p><p># 特定的用户<br />if current_user_only:<br />&#160; &#160; kwargs[ &#039;user&#039; ] = current_user</p><p># 根据标题查询<br />if title_search_query != &#039;&#039;:<br />&#160; &#160; kwargs[ &#039;title__icontains&#039; ] = title_search_query</p><p># 应用所有的查询<br />entries = Entry.objects.filter( **kwargs )<br /># 打印出所有的结果检查<br />print entries </p><br /><p>用这种方式，在Q object 方式下，是有问题的，要采用如下方式：</p><p>程序代码 程序代码</p><p>kwargs = { &#039;deleted_datetime__isnull&#039;: True }<br />args = ( Q( title__icontains = &#039;Foo&#039; ) | Q( title__icontains = &#039;Bar&#039; ) )<br />entries = Entry.objects.filter( *args, **kwargs )</p><br /><p>什么是 Q Object 方式，参考：<br /><a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects" rel="nofollow">https://docs.djangoproject.com/en/dev/t … -q-objects</a></p>]]></description>
			<author><![CDATA[dummy@example.com (xuyg)]]></author>
			<pubDate>Thu, 05 Feb 2015 07:46:47 +0000</pubDate>
			<guid>http://www.itecfun.com/viewtopic.php?pid=162#p162</guid>
		</item>
		<item>
			<title><![CDATA[django model filter 条件过滤，及多表连接查询、反向查询，某字段的distinct]]></title>
			<link>http://www.itecfun.com/viewtopic.php?pid=156#p156</link>
			<description><![CDATA[<p><strong>1.多表连接查询：当我知道这点的时候顿时觉得django太NX了。</strong><br />&#160; class A(models.Model):<br />&#160; &#160; name = models.CharField(u&#039;名称&#039;)<br />&#160; class B(models.Model):<br />&#160; &#160; aa = models.ForeignKey(A)<br />B.objects.filter(aa__name__contains=&#039;searchtitle&#039;)</p><p><strong>1.5 我叫它反向查询，后来插入记录1.5，当我知道的时候瞬间就觉得django太太太NX了。</strong><br />&#160; class A(models.Model):<br />&#160; &#160; name = models.CharField(u&#039;名称&#039;)<br />&#160; class B(models.Model):<br />&#160; &#160; aa = models.ForeignKey(A,related_name=&quot;FAN&quot;)<br />&#160; &#160; bb = models.CharField(u&#039;名称&#039;)<br />&#160; 查A: A.objects.filter(FAN__bb=&#039;XXXX&#039;)，都知道related_name的作用，A.FAN.all()是一组以A为外键的B实例，可前面这样的用法是查询出所有(B.aa=A且B.bb=XXXX)的A实例，然后还可以通过__各种关系查找，真赤激！！！</p><p><strong>2.条件选取querySet的时候，filter表示=，exclude表示!=。</strong><br />querySet.distinct()&#160; 去重复<br />__exact&#160; &#160; &#160; &#160; 精确等于 like &#039;aaa&#039;<br /> __iexact&#160; &#160; 精确等于 忽略大小写 ilike &#039;aaa&#039;<br /> __contains&#160; &#160; 包含 like &#039;%aaa%&#039;<br /> __icontains&#160; &#160; 包含 忽略大小写 ilike &#039;%aaa%&#039;，但是对于sqlite来说，contains的作用效果等同于icontains。<br />__gt&#160; &#160; 大于<br />__gte&#160; &#160; 大于等于<br />__lt&#160; &#160; 小于<br />__lte&#160; &#160; 小于等于<br />__in&#160; &#160; &#160;存在于一个list范围内<br />__startswith&#160; &#160;以...开头<br />__istartswith&#160; &#160;以...开头 忽略大小写<br />__endswith&#160; &#160; &#160;以...结尾<br />__iendswith&#160; &#160; 以...结尾，忽略大小写<br />__range&#160; &#160; 在...范围内<br />__year&#160; &#160; &#160; &#160;日期字段的年份<br />__month&#160; &#160; 日期字段的月份<br />__day&#160; &#160; &#160; &#160; 日期字段的日<br />__isnull=True/False</p><p>例子：<br />&gt;&gt; q1 = Entry.objects.filter(headline__startswith=&quot;What&quot;)<br />&gt;&gt; q2 = q1.exclude(pub_date__gte=datetime.date.today())<br />&gt;&gt; q3 = q1.filter(pub_date__gte=datetime.date.today())<br />&gt;&gt;&gt; q = q.filter(pub_date__lte=datetime.date.today())<br />&gt;&gt;&gt; q = q.exclude(body_text__icontains=&quot;food&quot;)</p><p>即q1.filter(pub_date__gte=datetime.date.today())表示为时间&gt;=now，q1.exclude(pub_date__gte=datetime.date.today())表示为&lt;=now</p><p>2013/12/12补充：<br />“在django models中取得一个字段的distinct值”。就是select distinct xxx&#160; from table_name ...这样的功能。使用values会生成ValuesQuerySet(形如N个dict组成的list)，猜测大数据无额外性能影响，毕竟queryset系列都是使用时才查询操作的。<br />xxxx.objects.values(&quot;field_name&quot;).distinct()<br />#或者<br />xxxx.objects.distinct().values(&quot;field_name&quot;) <br />这两句生成的sql语句相同，原帖地址：http://blog.csdn.net/tsbob/article/details/1340293。</p><p><strong>关于缓存：</strong><br />queryset是有缓存的，a = A.objects.all(),print [i for i in a].第一次执行打印会查询数据库，然后结果会被保存在queryset内置的cache中，再执行print的时候就会取自缓存。<br />很多时候会遇到仅需判断queryset是否为空的情况，可以1. if queryset:pass 2.if queryset.count&gt;0:pass 3.if queryset.exists():pass. 三种方式性能依次提升。<br />当queryset非常巨大时，cache会成为问题。此时可以queryset.iterator()，迭代器的用处就不多说了，根据具体需求情况使用。</p><p>来源：<a href="http://my.oschina.net/u/993130/blog/209460" rel="nofollow">开源中国</a></p>]]></description>
			<author><![CDATA[dummy@example.com (xuyg)]]></author>
			<pubDate>Thu, 05 Feb 2015 01:04:28 +0000</pubDate>
			<guid>http://www.itecfun.com/viewtopic.php?pid=156#p156</guid>
		</item>
	</channel>
</rss>
