Задать вопрос

Тел: +7 965 3737 888

413

Просмотров

1

Ответов

Bitwise operator queryset filter

<p>This snippet for django-1.2 allows you to use bitwise operators without using QuerySet.extra()</p>
from django.db.models import *
from somewhere import FQ

class BitWise(Model):
    type = CharField(max_length=8)
    value = IntegerField()

    def __unicode__(self):
        return '%s - %d' % (self.type, self.value)

&gt;&gt;&gt; BitWise.objects.create(type='django', value=1)
&lt;BitWise: django - 1&gt;
&gt;&gt;&gt; BitWise.objects.create(type='osso', value=3)
&lt;BitWise: osso - 3&gt;
&gt;&gt;&gt; BitWise.objects.create(type='osso', value=7)
&lt;BitWise: osso - 7&gt;
&gt;&gt;&gt; BitWise.objects.filter(FQ(F('value') &amp; 1, 'gt', 0))
[&lt;BitWise: django - 1&gt;, &lt;BitWise: osso - 3&gt;, &lt;BitWise: osso - 7&gt;]
&gt;&gt;&gt; BitWise.objects.filter(FQ(F('value') &amp; 2, 'gt', 0))
[&lt;BitWise: osso - 3&gt;, &lt;BitWise: osso - 7&gt;]
&gt;&gt;&gt; BitWise.objects.filter(FQ(F('value') &amp; 1, 'gt', 0) &amp; Q(type='django'))
[&lt;BitWise: django - 1&gt;]

Вопрос полезен? Да0/Нет0
file_4561.py(3.3Кб)
None

Ответы (1):

Ответmikesperanza:16.08.2013
Ответ полезен? Да0/Нет0

Very nice and useful for anyone stuck on pre-1.5

However, I found you also need to implement the relabel_aliases on the FExpression, otherwise, in subqueries, the aliases will not be used and the query will not run correctly. Something like this:

def relabel_aliases(self, change_map):
    if hasattr(self.left_expression, "relabel_aliases"):
        self.left_expression.relabel_aliases(change_map)
    if hasattr(self.right_expression, "relabel_aliases"):
        self.right_expression.relabel_aliases(change_map)