@@ -277,7 +277,9 @@ def execute_sql(
277
277
try :
278
278
query = self .build_query (
279
279
# Avoid $project (columns=None) if unneeded.
280
- columns if self .query .annotations or not self .query .default_cols else None
280
+ columns
281
+ if self .query .annotations or not self .query .default_cols or self .query .distinct
282
+ else None
281
283
)
282
284
except EmptyResultSet :
283
285
return iter ([]) if result_type == MULTI else None
@@ -378,7 +380,7 @@ def check_query(self):
378
380
raise NotSupportedError ("QuerySet.datetimes() is not supported on MongoDB." )
379
381
if "datefield" in self .query .annotations :
380
382
raise NotSupportedError ("QuerySet.dates() is not supported on MongoDB." )
381
- raise NotSupportedError ("QuerySet.distinct() is not supported on MongoDB." )
383
+ # raise NotSupportedError("QuerySet.distinct() is not supported on MongoDB.")
382
384
if self .query .extra :
383
385
if any (key .startswith ("_prefetch_related_" ) for key in self .query .extra ):
384
386
raise NotSupportedError ("QuerySet.prefetch_related() is not supported on MongoDB." )
@@ -397,6 +399,20 @@ def build_query(self, columns=None):
397
399
)
398
400
query .combinator_pipeline = self .get_combinator_queries ()
399
401
else :
402
+ # If we query distinct
403
+ if self .query .distinct :
404
+ distinct_fields = self .get_project_fields (columns , force_expression = True )
405
+ if not query .aggregation_pipeline :
406
+ query .aggregation_pipeline = []
407
+ query .aggregation_pipeline .extend (
408
+ [
409
+ {"$group" : {"_id" : distinct_fields }},
410
+ {"$addFields" : {key : f"$_id.{ key } " for key in distinct_fields }},
411
+ ]
412
+ )
413
+ if "_id" not in distinct_fields :
414
+ query .aggregation_pipeline .append ({"$unset" : "_id" })
415
+
400
416
query .project_fields = self .get_project_fields (columns , ordering_fields )
401
417
# If columns is None, then get_project_fields() won't add
402
418
# ordering_fields to $project. Use $addFields (extra_fields) instead.
@@ -767,7 +783,7 @@ def build_query(self, columns=None):
767
783
# Avoid $project (columns=None) if unneeded.
768
784
columns = (
769
785
compiler .get_columns ()
770
- if compiler .query .annotations or not compiler .query .default_cols
786
+ if self .query .annotations or not self .query .default_cols or self . query . distinct
771
787
else None
772
788
)
773
789
subquery = compiler .build_query (columns )
0 commit comments