django ormを使ってexists条件フィルタの例を書きます。


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ファイルの下にいます。間違いないです。しかし、アプリをまたぐと以下のエラーが発生します。
users.HostToApp.abj:(fields.E 300)Field defines a relation with model'Appplication',which is ether not installed,or is abstract.
users.HostToApp.abj:(fields.E 307)The field users.HostToApp.abj was declead with a lazy reference to'users.appliation'は、but app'users'doesn't provide model'appication.
ソリューション:
1、
from xxxx.models import Appplication
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条件フィルタリングの例を書いたら、小編集が皆さんに提供した内容の全部です。参考にしてほしいです。よろしくお願いします。