使用 django orm 寫 exists 條件過濾實例
要用django的orm表達sql的exists子查詢,是個比較麻煩的事情,需要做兩部來完成
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定義一個額外字段 recent_comment=Exists(recent_comments),).filter(recent_comment=True) # 在條件中通過檢查額外字段實現(xiàn)exists子查詢過濾
這種方式比較麻煩,有其它簡便方式的歡迎分享
官網(wǎng)參考: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#filtering-on-a-subquery-expression
補充知識:關(guān)于使用django orm 時的坑
跨app 時外鍵報錯
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 都在一個models 文件下時不會報錯。 但是一旦出現(xiàn)跨app 時會報以下錯誤:
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 條件過濾實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 怎樣打開XML文件?xml文件如何打開?2. ASP和PHP文件操作速度的對比3. ASP替換、保存遠程圖片實現(xiàn)代碼4. ASP中Server.HTMLEncode用法(附自定義函數(shù))5. ASP.Net MVC利用NPOI導(dǎo)入導(dǎo)出Excel的示例代碼6. adodb.recordset.open(rs.open)方法參數(shù)詳解7. 使用AJAX實現(xiàn)UTF8編碼表單提交到GBK編碼腳本無亂碼的解決方法8. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識)9. WML教程之文本框控件Input10. asp文件如何打開
