[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
Django ORM自带的defer和only方法虽说不像filter, exclude,
order_by这几个方法那么常见,但用起来还是可以优化数据库查询的。今天小编我就带你看看如何使用这两种方法。
Defer方法
Defer方法的用途是查询数据库时跳过指定的字段,比如下面查询时将跳过每篇Entry的headline和body字段。当你不需要在查询结果中使用headline和body字段时,使用defer方法可以防止将headline和body载入内存,从而节省空间。一篇文章可能没啥关系,但文章很多时,节省的内存空间不可忽视。
Entry.objects.defer("headline", "body")
Defer方法可以和filter, exclude方法联用,其顺序无关紧要,如下所示:
Entry.objects.defer("body").filter(rating=5).defer("headline")
如果你要载入所有字段,只需要设置defer(None)
my_queryset.defer(None)
Only方法
Only方法与defer方法作用类时,只不过only方法是指定需要载入的字段。比如下面查询将只会载入body和pub_date。
Entry.objects.only("body", "pub_date")
使用only方法时一定要非常注意它的顺序,它的执行以最后一个为准。下例将只会载入headline。
Entry.objects.only("body", "rating").only("headline")
only方法与defer方法可以联用,但一定要注意先后顺序。下例只会载入headline。
Entry.objects.only("headline", "body").defer("body")