Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fixed #2936, #6500 -- Added a __hash__() method to Models (since we i…

…mplement our own __eq__ method).

git-svn-id: http://code.djangoproject.com/svn/django/trunk@7132 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 343fa35a2cd4bb22457eb9031fa23c751c13f09d 1 parent f1a24be
@malcolmt malcolmt authored
Showing with 14 additions and 0 deletions.
  1. +3 −0  django/db/models/base.py
  2. +11 −0 tests/modeltests/basic/models.py
View
3  django/db/models/base.py
@@ -135,6 +135,9 @@ def __eq__(self, other):
def __ne__(self, other):
return not self.__eq__(other)
+ def __hash__(self):
+ return hash(self._get_pk_val())
+
def __init__(self, *args, **kwargs):
dispatcher.send(signal=signals.pre_init, sender=self.__class__, args=args, kwargs=kwargs)
View
11 tests/modeltests/basic/models.py
@@ -5,6 +5,11 @@
This is a basic model with only two non-primary-key fields.
"""
+try:
+ set
+except NameError:
+ from sets import Set as set
+
from django.db import models
class Article(models.Model):
@@ -389,4 +394,10 @@ def __unicode__(self):
>>> a.save()
>>> Article.objects.get(pk=a.id).headline
u'\u6797\u539f \u3081\u3050\u307f'
+
+# Model instances have a hash function, so they can be used in sets or as
+# dictionary keys. Two models compare as equal if their primary keys are equal.
+>>> s = set([a10, a11, a12])
+>>> Article.objects.get(headline='Article 11') in s
+True
"""
Please sign in to comment.
Something went wrong with that request. Please try again.