使用 django orm 寫 exists 條件過濾實(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) # 在條件中通過檢查額外字段實(shí)現(xiàn)exists子查詢過濾
這種方式比較麻煩,有其它簡(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 條件過濾實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python設(shè)置windows桌面壁紙的實(shí)現(xiàn)代碼
每天換一個(gè)壁紙,每天好心情。喜歡的朋友可以參考下2013-01-01pytorch模型部署 pth轉(zhuǎn)onnx的方法
這篇文章主要介紹了pytorch模型部署 pth轉(zhuǎn)onnx的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-05-05pip 20.3 新版本發(fā)布!即將拋棄 Python 2.x(推薦)
這篇文章主要介紹了pip 20.3 新版本發(fā)布!即將拋棄 Python 2.x,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12基于Python實(shí)現(xiàn)給喜歡的主播自動(dòng)發(fā)彈幕
這篇文章主要介紹了python如何實(shí)現(xiàn)給喜歡的主播自動(dòng)發(fā)彈幕的功能,文中的示例代碼對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的朋友可以了解下2021-12-12keras 回調(diào)函數(shù)Callbacks 斷點(diǎn)ModelCheckpoint教程
這篇文章主要介紹了keras 回調(diào)函數(shù)Callbacks 斷點(diǎn)ModelCheckpoint教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2020-06-06Python3實(shí)現(xiàn)連接SQLite數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了Python3實(shí)現(xiàn)連接SQLite數(shù)據(jù)庫(kù)的方法,在Python數(shù)據(jù)庫(kù)編程中有著廣泛的應(yīng)用,需要的朋友可以參考下2014-08-08Python實(shí)現(xiàn)多子圖繪制系統(tǒng)的示例詳解
這篇文章主要介紹了如何利用python實(shí)現(xiàn)多子圖繪制系統(tǒng),文中的示例代碼講解詳細(xì),具有一定的的參考價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-09-09