构造一个连接的 django 查询
我正在与另一个系统上的遗留数据库进行交互,因此模型是一成不变的,不是很 django-ey。
我的 models.py
:
class Site(models.Model):
site_code = models.CharField(max_length=30, primary_key=True)
name = models.CharField(unique=True, max_length=300)
class Document(models.Model):
id = models.IntegerField(primary_key=True)
site_ref = models.ForeignKey(Site)
description = models.CharField(max_length=1500)
class DocumentStatusCategory(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(unique=True, max_length=90)
class DocumentStatus(models.Model):
id = models.IntegerField(primary_key=True)
document = models.ForeignKey(Document)
status = models.ForeignKey(DocumentStatusCategory)
changed_by = models.ForeignKey(User)
created_at = models.DateTimeField()
在我的 views.py
中,我想检索包含属于指定 的所有
(例如 Document
对象的查询集站点site_ref=mysite
)不具有任何具有 status=4
的相关 DocumentStatus
对象>。
知道如何将其作为单个(非 sql 密集型)行来完成吗?
I'm interacting with a legacy db on another system, so the models are written in stone and not very django-ey.
My models.py
:
class Site(models.Model):
site_code = models.CharField(max_length=30, primary_key=True)
name = models.CharField(unique=True, max_length=300)
class Document(models.Model):
id = models.IntegerField(primary_key=True)
site_ref = models.ForeignKey(Site)
description = models.CharField(max_length=1500)
class DocumentStatusCategory(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(unique=True, max_length=90)
class DocumentStatus(models.Model):
id = models.IntegerField(primary_key=True)
document = models.ForeignKey(Document)
status = models.ForeignKey(DocumentStatusCategory)
changed_by = models.ForeignKey(User)
created_at = models.DateTimeField()
In my views.py
I want to retrieve a queryset with all the Document
objects that belong to a specified Site
(say site_ref=mysite
) which do not have any related DocumentStatus
objects with status=4
.
Any idea how I can do this as a single (non-sql intensive) line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不完全是一个查询,但我认为如果不使用原始 SQL 就无法实现这一点。我认为两个查询还不错。
我应该提到的是,上面假设 Document 和 DocumentStatus 之间的反向关系是
documentstatus_set
。您可以明确地说明反向关系,如下所示:然后查询变为:
Not exactly one query, but I don't think that's achievable without going down to raw sql. Two queries isn't bad though I suppose.
I should mention that the above assumes that the reverse relation between Document and DocumentStatus is
documentstatus_set
. You can explicitly state what the reverse relation is like so:Then the query becomes: