toastdriven/django-haystack — Issue #446: SearchResult objects do not support comparison (__eq__, __ne__, __hash__)
Author: jacksonqt
Created: 2011-11-19 01:19:25+00:00
State: open

Comparing SearchResult objects with the == operator always returns false.

>>> sqs1 = SearchQuerySet().all()
>>> sqs2 = SearchQuerySet().all()
>>> sqs1[0] == sqs2[0]
False
# This should return True

Additionally, SearchResult objects don't support sets.

Solution:

Define __eq__(), __ne__() and __hash__() for SearchResult in models.py.

def __eq__(self, other):
try:
return (self.app_label == other.app_label) and (self.model_name == other.model_name) and (self.pk == other.pk)
except AttributeError:
return False

def __ne__(self, other):
try:
return (self.app_label != other.app_label) or (self.model_name != other.model_name) or (self.pk != other.pk)
except AttributeError:
return False

def __hash__(self):
hash_string = "%s%s%s" % (self.app_label, self.model_name, self.pk)
return hash_string.__hash__()

Notes:

The try except is required to support set(SearchQuerySet).

__hash__ is required to support set comparisons when a SearchQuerySet is converted to a set.