Q:

why is Django MultipleObjectsReturned Error hogging memory?

I am using Django 1.9.10:
I have a model called Details has a unique_id column which is indexed: 
 try:
     detail = Detail.objects.get(unique_id=UUID)
 except MultipleObjectsReturned as m:
     logger.error("uuid {} returned multiple objects - {}".format(UUID, str(m)))

Due to some error in code UUID=None this resulted in MultipleObjectsReturned error getting raised. but we noticed that almost 2-GB of memory is getting used up and it is slowing the system down a lot. 
On printing str(m) in the error logs we found following error

MultipleObjectsReturned: get() returned more than one Details -- it returned 451424!

My Question is why is Django fetching so much data in memory just to raise an error? Django can just fetch the count?
I know I can use filter() to over come this issue but I am just surprised by this and want to understand why django is doing this?    

A:

Because that's how it's done internally: 
def get(self, *args, **kwargs):
    """
    Perform the query and return a single object matching the given
    keyword arguments.
    """
    clone = self.filter(*args, **kwargs) # calling `filter()` inside
    if self.query.can_filter() and not self.query.distinct_fields:
        clone = clone.order_by()
    num = len(clone)
    if num == 1:
        return clone._result_cache[0]
    if not num:
        raise self.model.DoesNotExist(
            "%s matching query does not exist." %
            self.model._meta.object_name
        )
    raise self.model.MultipleObjectsReturned(
        "get() returned more than one %s -- it returned %s!" %
        (self.model._meta.object_name, num)
    )

See the full source here.
I guess you wonder why it can't just fetch the number? Because it will make two requests to the database instead of one. One request to fetch the count and one request to fetch the data.
How can you fix it? You may change your application logic to avoid this situation. Assert that UUID is not None. Or fetch count before making an actual query.
Docs about get: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-a-single-object-with-get

