使用 django orm 寫 exists 條件過(guò)濾實(shí)例
要用django的orm表達(dá)sql的exists子查詢,是個(gè)比較麻煩的事情,需要做兩部來(lái)完成
from django.db.models import Exists, OuterRef # 1. 定義子查詢條件relative_comments = Comment.objects.filter( post=OuterRef(’pk’), # 注意外鍵關(guān)聯(lián)方式:post為Comment表的字段,pk表示關(guān)聯(lián)另一表主鍵) # 2. 使用annotate和filter共同定義子查詢Post.objects.annotate( # 使用exists定義一個(gè)額外字段 recent_comment=Exists(recent_comments),).filter(recent_comment=True) # 在條件中通過(guò)檢查額外字段實(shí)現(xiàn)exists子查詢過(guò)濾
這種方式比較麻煩,有其它簡(jiǎn)便方式的歡迎分享
官網(wǎng)參考: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#filtering-on-a-subquery-expression
補(bǔ)充知識(shí):關(guān)于使用django orm 時(shí)的坑
跨app 時(shí)外鍵報(bào)錯(cuò)
class Host(models.Model):nid = models.AutoField(primary_key=True)hostname = models.CharField(max_length=32, db_index=True)ip = models.GenericIPAddressField(protocol=“ipv4”, db_index=True)port = models.IntegerField()# b = models.ForeignKey(to=“Business”, to_field=‘id’)class HostToApp(models.Model):hobj = models.ForeignKey(to=‘Host’, to_field=‘nid’)aobj = models.ForeignKey(to=‘Application’, to_field=‘id’)class Application(models.Model):name = models.CharField(max_length=32)
以上 model 都在一個(gè)models 文件下時(shí)不會(huì)報(bào)錯(cuò)。 但是一旦出現(xiàn)跨app 時(shí)會(huì)報(bào)以下錯(cuò)誤:
users.HostToApp.aobj: (fields.E300) Field defines a relation with model ‘Application’, which is either not installed, or is abstract.users.HostToApp.aobj: (fields.E307) The field users.HostToApp.aobj was declared with a lazy reference to ‘users.application’, but app ‘users’ doesn’t provide model ‘a(chǎn)pplication’.
解決方案:
1、
from xxxx.models import Application
2、
class HostToApp(models.Model):hobj = models.ForeignKey(to=‘Host’, to_field=‘nid’)aobj = models.ForeignKey(to=‘xxxx.Application’, to_field=‘id’)
第二步很重要
以上這篇使用 django orm 寫 exists 條件過(guò)濾實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JAMon(Java Application Monitor)備忘記2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法4. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法5. Docker容器如何更新打包并上傳到阿里云6. VMware中如何安裝Ubuntu7. Springboot 全局日期格式化處理的實(shí)現(xiàn)8. python 浮點(diǎn)數(shù)四舍五入需要注意的地方9. idea配置jdk的操作方法10. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問(wèn)題
