Q model and or query giving incorrect result

Viewed 23

I want perform below SQL query using Q models

SELECT * FROM motor_vehicle_collision.collision_data_collisiondetails where (numberOfCyclistInjured > 0 or numberOfCyclistKilled > 0) and (longitude != '' and latitude != '');

for that I have written below query

   query = Q(numberOfCyclistInjured__gt=0)
    query.add(Q(numberOfCyclistKilled__gt=0), Q.OR)
    query.add(~Q(latitude=''), Q.AND)
    query.add(~Q(longitude=''), Q.AND)

but still I am getting data having latitude/longitude empty, how should I rectify it?

1 Answers

You can work with:

query = (Q(numberOfCyclistInjured__gt=0) | Q(numberOfCyclistKilled__gt=0))
    & ~Q(longitude='')
    & ~Q(latitude=''))

This makes it also more explicit how you bind the conditions together.

Related