您的位置:首页 > 编程语言 > Go语言

django正向与反向查询

2017-08-20 22:11 447 查看
Django版本1.11.4

Django ORM model 中的filter 条件过滤,及多表连接查询、反向查询,某个字段的distinct

多表连接查询:

from django.db import models

# Create your models here.

class H_Type(models.Model):
hcity = models.CharField(max_length=10)
htypes = models.CharField(max_length=20)

def __str__(self):
return self.hcity + "-" + self.htypes

class House(models.Model):
h_name = models.CharField(max_length=30)
h_detail =models.TextField(blank=True, null=True)
h_date = models.DateField()
h_image = models.ImageField(upload_to='House_image')
houses = models.ForeignKey(H_Type)

def __str__(self):
return self.h_name


python manage.py shell进入django shell终端

from House.models import H_Type,House

#查询上海的全部房源
House.objects.filter(houses__hcity="上海")
#查询结果<QuerySet [<House: 浦东新区>, <House: 浦东二区>]>

#统计上海房源的数量
House.objects.filter(houses__hcity="上海").count()
#查询结果 2

#根据id排序(升序)
House.objects.filter(houses__hcity="上海").order_by('id')
#排序结果<QuerySet [<House: 浦东新区>, <House: 浦东二区>]>

#降序
House.objects.filter(houses__hcity="上海").order_by('-id')
#<QuerySet [<House: 浦东二区>, <House: 浦东新区>]>

#查询名字中包含一个北的所有房源
House.objects.filter(houses__hcity__contains="北")
#<QuerySet [<House: 昌平宏福苑>, <House: 昌平宏福苑一区>]>


反向查询。

from django.db import models
# Create your models here.
class H_Type(models.Model):
hcity = models.CharField(max_length=10)
htypes = models.CharField(max_length=20)

def __str__(self):
return self.hcity + "-" + self.htypes

class House(models.Model):
h_name = models.CharField(max_length=30)
h_detail =models.TextField(blank=True, null=True)
h_date = models.DateField()
h_image = models.ImageField(upload_to='House_image')
houses = models.ForeignKey(H_Type)

def __str__(self):
return self.h_name


python manage.py shell

from House.models import H_Type,House
#查询房屋名字来获取属于哪个地区
H_Type.objects.filter(house__h_name="昌平宏福苑")
#<QuerySet [<H_Type: 北京-高档小区>]>


2.条件选取querySet的时候,filter表示=,exclude表示!=。

querySet.distinct()  去重复
__exact        精确等于 like 'aaa'
__iexact    精确等于 忽略大小写 ilike 'aaa'
__contains    包含 like '%aaa%'
__icontains    包含 忽略大小写 ilike '%aaa%',但是对于sqlite来说,contains的作用效果等同于icontains。
__gt    大于
__gte    大于等于
__lt    小于
__lte    小于等于
__in     存在于一个list范围内
__startswith   以...开头
__istartswith   以...开头 忽略大小写
__endswith     以...结尾
__iendswith    以...结尾,忽略大小写
__range    在...范围内
__year       日期字段的年份
__month    日期字段的月份
__day        日期字段的日
__isnull=True/False


例子:

h1 = Entry.objects.filter(headline__startswith="What")
h2 = h1.exclude(pub_date__gte=datetime.date.today())
h3 = h1.filter(pub_date__gte=datetime.date.today())
h.filter(pub_date__lte=datetime.date.today())
h.exclude(body_text__icontains="food")


即h1.filter(pub_date__gte=datetime.date.today())表示为时间>=now,h1.exclude(pub_date__gte=datetime.date.today())表示为<=now

以下内容借鉴

“在django models中取得一个字段的distinct值”。就是select distinct from table_name …这样的功能。使用values会生成ValuesQuerySet(形如N个dict组成的list),大数据无额外性能影响,毕竟queryset系列都是使用时才查询操作的。

xxxx.objects.values(“field_name”).distinct()

或者

xxxx.objects.distinct().values(“field_name”)

这两句生成的sql语句相同,原帖地址:http://blog.csdn.net/tsbob/article/details/1340293

关于缓存:

queryset是有缓存的,a = A.objects.all(),print [i for i in a].第一次执行打印会查询数据库,然后结果会被保存在queryset内置的cache中,再执行print的时候就会取自缓存。

很多时候会遇到仅需判断queryset是否为空的情况,可以1. if queryset:pass 2.if queryset.count>0:pass 3.if queryset.exists():pass. 三种方式性能依次提升。

当queryset非常巨大时,cache会成为问题。此时可以queryset.iterator(),迭代器的用处就不多说了,根据具体需求情况使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django