Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Malcolm Tredinnick authored February 19, 2008
3  django/db/models/base.py
@@ -135,6 +135,9 @@ def __eq__(self, other):
135 135
     def __ne__(self, other):
136 136
         return not self.__eq__(other)
137 137
 
  138
+    def __hash__(self):
  139
+        return hash(self._get_pk_val())
  140
+
138 141
     def __init__(self, *args, **kwargs):
139 142
         dispatcher.send(signal=signals.pre_init, sender=self.__class__, args=args, kwargs=kwargs)
140 143
 
11  tests/modeltests/basic/models.py
@@ -5,6 +5,11 @@
5 5
 This is a basic model with only two non-primary-key fields.
6 6
 """
7 7
 
  8
+try:
  9
+    set
  10
+except NameError:
  11
+    from sets import Set as set
  12
+
8 13
 from django.db import models
9 14
 
10 15
 class Article(models.Model):
@@ -389,4 +394,10 @@ def __unicode__(self):
389 394
 >>> a.save()
390 395
 >>> Article.objects.get(pk=a.id).headline
391 396
 u'\u6797\u539f \u3081\u3050\u307f'
  397
+
  398
+# Model instances have a hash function, so they can be used in sets or as
  399
+# dictionary keys. Two models compare as equal if their primary keys are equal.
  400
+>>> s = set([a10, a11, a12])
  401
+>>> Article.objects.get(headline='Article 11') in s
  402
+True
392 403
 """

0 notes on commit 343fa35

Please sign in to comment.
Something went wrong with that request. Please try again.