开发者

Get all object with empty set of related ones

开发者 https://www.devze.com 2023-02-01 01:00 出处:网络
I\'ve got two models: class Content(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True)

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 accomplis开发者_运维问答h that (unfortunately aggregation doesn't work with generic relations and I can't count items).


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:

SELECT *, `foobar_bar`.`show` AS `show` FROM `foobar_foo` LEFT OUTER JOIN `foobar_bar` 
    ON (`foobar_foo`.`id` = `foobar_bar`.`object_id` and 
        ctype = `foobar_bar`.`content_type_id`) 
    WHERE show=TRUE OR show=NULL

I assumed that both models are in foobar application and ctype is content_type of model Foo. I haven't found way to do such query but we can do something like:

SELECT *, `foobar_bar`.`show` AS `show` FROM `foobar_foo` LEFT OUTER JOIN `foobar_bar` 
    ON (`foobar_foo`.`id` = `foobar_bar`.`object_id`
    WHERE (show=TRUE OR show=NULL) AND ctype = `foobar_bar`.`content_type_id`

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:

qs = Foo.objects.all()

qs.query.join((None, 'foobar_foo', None, None))
qs.query.join(('foobar_foo', 'foobar_bar', 'id', 'object_id'), promote=True)
foos.
qs = qs.extra(select = {'show': 'foobar_bar.show',},
              where = "(show=TRUE OR show=NULL) AND ctype = `foobar_bar`.`content_type_id`")

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号