最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用 django orm 寫 exists 條件過濾實(shí)例

 更新時(shí)間:2020年05月20日 17:11:46   作者:xufwind  
這篇文章主要介紹了使用 django orm 寫 exists 條件過濾實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧

要用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)文章

最新評(píng)論

巴里| 安阳县| 林芝县| 绥棱县| 汉阴县| 芜湖县| 合江县| 桐城市| 武冈市| 应城市| 东明县| 金昌市| 昭觉县| 霍邱县| 高平市| 墨脱县| 陆河县| 天峻县| 古田县| 绩溪县| 陕西省| 屏东县| 万载县| 岑溪市| 海林市| 平邑县| 隆尧县| 托里县| 新沂市| 漯河市| 镇巴县| 西充县| 达孜县| 儋州市| 胶州市| 迁安市| 苏尼特右旗| 黄梅县| 凤台县| 祁连县| 潼南县|