Search code examples
djangodjango-q

Q model and or query giving incorrect result


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?


Solution

  • 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.