Strange behavior with complex Q object filter queries in Django

Posted by HWM-Rocker on Stack Overflow See other posts from Stack Overflow or by HWM-Rocker
Published on 2010-04-27T02:26:48Z Indexed on 2010/04/27 2:33 UTC
Read the original article Hit count: 291

Filed under:
|
|

Hi I am trying to write a tagging system for Django, but today I encountered a strange behavior in filter or the Q object (django.db.models.Q).

I wrote a function, that converts a search string into a Q object. The next step would be to filter the TaggedObject with these query. But unfortunately I get a strange behavior.

when I search (id=20) => Q: (AND: ('tags__tag__id', 20)) and it returns 2 Taged Objects with the ID 1127 and 132

when I search (id=4) => Q: (AND: ('tags__tag__id', 4)) and it returns also 2 Objects, but this time 1180 and 1127

until here is everything fine, but when i make a little bit more complex query like (id=4) or (id=20) => Q: (OR: ('tags__tag__id', 4), ('tags__tag__id', 20)) then it returns 4(!) Objects 1180, 1127, 1127, 132

But the object with the ID 1127 is returned twice, but thats not the behaviour I want. Do I have to live with it, and uniqify that list or can I do something different. The representation of the Q object looks fine for me.

But the worst is now, when I search for (id=20) and (id=4) => Q: (AND: ('tags__tag__id', 20), ('tags__tag__id', 4)) then it returns no object at all. But why? The representation should be ok and the object with the id 1127 is tagged by both. What am I missing?

Here are also the relevant parts of the classes, that are involved:

class TaggedObject(models.Model):
    """
        class that represent a tagged object
    """
    tags = generic.GenericRelation('ObjectTagBridge',
                                   blank=True, null=True)

class ObjectTagBridge(models.Model):
    """
        Help to connect a generic object to a Tag.
    """
    # pylint: disable-msg=W0232,R0903
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    tag = models.ForeignKey('Tag')

class Tag(models.Model):
    ...

Thanks for your help

© Stack Overflow or respective owner

Related posts about django

Related posts about search