国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

使用 django orm 寫 exists 條件過濾實例

瀏覽:2日期:2024-10-02 09:40:04

要用django的orm表達sql的exists子查詢,是個比較麻煩的事情,需要做兩部來完成

from django.db.models import Exists, OuterRef # 1. 定義子查詢條件relative_comments = Comment.objects.filter( post=OuterRef(’pk’), # 注意外鍵關聯方式:post為Comment表的字段,pk表示關聯另一表主鍵) # 2. 使用annotate和filter共同定義子查詢Post.objects.annotate( # 使用exists定義一個額外字段 recent_comment=Exists(recent_comments),).filter(recent_comment=True) # 在條件中通過檢查額外字段實現exists子查詢過濾

這種方式比較麻煩,有其它簡便方式的歡迎分享

官網參考: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#filtering-on-a-subquery-expression

補充知識:關于使用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 文件下時不會報錯。 但是一旦出現跨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 ‘application’.

解決方案:

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 條件過濾實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Django
相關文章:
主站蜘蛛池模板: 隆回县| 普兰店市| 固原市| 视频| 大冶市| 壶关县| 仪征市| 东丰县| 黎平县| 邮箱| 武强县| 斗六市| 玉田县| 锡林浩特市| 颍上县| 丽水市| 涞水县| 临城县| 宜阳县| 武义县| 册亨县| 福州市| 赣州市| 东乡县| 美姑县| 府谷县| 永定县| 莱芜市| 新安县| 武汉市| 栾川县| 金乡县| 资源县| 民权县| 鄢陵县| 前郭尔| 兴义市| 新营市| 洪洞县| 枝江市| 佛坪县|