V
V
Vladimir Kuts2018-11-16 15:09:40
MySQL
Vladimir Kuts, 2018-11-16 15:09:40

Bit request with F?

There is a User model with an integer field alert_flags.
I perform bitwise operations with each instance - everything is clear:

In [71]: User.objects.all().count()
Out[71]: 554

In [72]: len(filter(lambda x: x!=0, [im.alert_flags & 0b00010000 for im in User.objects.all()]))
Out[72]: 517

In [73]: len(filter(lambda x: x==0, [im.alert_flags & 0b00010000 for im in User.objects.all()]))
Out[73]: 37

Executing an ORM query leads to completely unexpected results:
In [74]: User.objects.filter(alert_flags=F('alert_flags').bitand(0b00010000)).count()
Out[74]: 63

How can you correctly implement a bitwise query to the database through the ORM?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-11-16
@deliro

Any senseless at you request in SQL turns out. Approximately here such wording:
"Show me all users at whom flags are equal to flags & 0b00010000". All users will be included in the selection, such that the mask does not change their alert_flags using a bitwise AND.
Use annotate and then filter. Only right.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question