Home > Mobile >  Django query with conflicting fields returns duplicate answers
Django query with conflicting fields returns duplicate answers

Time:06-28

Query:

cameraSystems = DWCloudSystem.objects.filter(isShared=False).filter(company_key=comp)
cameraSystems = cameraSystems | DWCloudSystem.objects.filter(isShared=True).filter(location__owners=comp)

DWCloudSystem is a model with that contains:

"company_key" a foreign key representing a Company model object,
"location" a foreign key representing a place object,
"isShared" a Boolean field

A place object also contains a "owners" ManyToMany field for company objects.

Essentially the goal is to have a DWCloudSystem which is owned by a company which is at a place to be returned if isSharing is false

or ifSharing is true then any company that belongs to the place object will be able to access that DWCloudSystem along with its "owner" company which is represented by the company_key field (which may or may not be a member of the "owners" field that is apart of the place model)

The issue is this query is returning the same company twice even though isShared is set to True and thus the other query should be empty. Both work correctly if not combined.

CodePudding user response:

Use a single filter condition and use .distinct(…) [Django-doc] to return distinct DwCloudSystems:

from django.db.models import Q

DWCloudSystem.objects.filter(
    Q(isShared=False, company_key=comp) |
    Q(isShared=True, location__owners=comp)
).distinct()
  • Related