获取所有相关对象为空的对象
我有两个模型:
class Content(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = generic.GenericForeignKey()
show = models.BooleanField(default=False)
class Foo(models.Model):
rel = generic.GenericRelation(Content)
我想获取与相关内容对象(只有一个)具有 show==True
或根本没有相关对象的所有 Foo 方法。类似的东西:
Foo.objects.filter(Q(rel__show=True) | Q(rel__hasnone=True))
但是,当然,django 中没有像 hasnone
这样的东西。
有没有其他方法可以实现这一点(不幸的是,聚合不适用于通用关系,并且我无法计算项目)。
I've got two models:
class Content(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = generic.GenericForeignKey()
show = models.BooleanField(default=False)
class Foo(models.Model):
rel = generic.GenericRelation(Content)
And I want to get all Foo methods that's related content object (there would be only one) has show==True
or that doesn't have related object at all. Something like:
Foo.objects.filter(Q(rel__show=True) | Q(rel__hasnone=True))
But of course there's nothing like hasnone
in django.
Is there any other way in which I can accomplish that (unfortunately aggregation doesn't work with generic relations and I can't count items).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我想我的答案可以让我们中的一些人满意(不幸的是不是我)。
我需要的是 Django 不支持的 LEFT OUTER JOIN (用户声明的所有联接都是 INNER 联接),例如:
我假设两个模型都在 foobar 应用程序中,并且 ctype 是模型的 content_type <代码>Foo。我还没有找到执行此类查询的方法,但我们可以执行以下操作:
它不是令人满意的排他性(可以仅根据对象的 id 连接具有不同 ctype 的元组),但仍然有用。我在 链接文本。它会是这样的:
通常使用
query.join((,), Promotion=True)
让我们得到 LEFT QUERY JOIN 而不是 INNER,但我们只能传递一个 ON 参数,这太少了完全解决这个问题但仍然有用。Ok, I think I've answer that could satisfy some of us (unfortunately not me).
What I need was LEFT OUTER JOIN which Django doesn't support (all joins declared by user are INNER ones), something like:
I assumed that both models are in
foobar
application and ctype is content_type of modelFoo
. I haven't found way to do such query but we can do something like:It's not satisfactory exclusive (could join tuples with different ctype just basing on object's id) but is still useful. Way to do such query I found at link text. It'll be something like:
Generally using
query.join((,), promote=True)
gets us LEFT QUERY JOIN instead of INNER, but we can pass only one ON argument, which is too less to solve completely that problem but still useful.