django正向与反向查询

  • 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(),迭代器的用处就不多说了,根据具体需求情况使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值