Django

Code

Ticket #6500 (closed: fixed)

Opened 5 months ago

Last modified 5 months ago

Make models hashable

Reported by: Bastian Kleineidam <calvin@debian.org> Assigned to: nobody
Milestone: Component: Uncategorized
Version: SVN Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: 1 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 1

Description

The Model instances should be hashable so that tests like "instance in set([instance1, instance2])" actually succeed.

Attachments

0055-Make-models-hashable.patch (0.8 kB) - added by Bastian Kleineidam <calvin@debian.org> on 01/28/08 10:34:36.

Change History

01/28/08 10:34:36 changed by Bastian Kleineidam <calvin@debian.org>

  • attachment 0055-Make-models-hashable.patch added.

01/28/08 10:55:42 changed by pytechd <pytechd@gmail.com>

  • needs_better_patch changed.
  • needs_tests changed.
  • needs_docs changed.

Before adding this, please consider adding the app and model name into the hash as well as the PK. Otherwise the hashes of Article(pk=1) and Author(pk=1) are identical.

(follow-up: ↓ 4 ) 01/28/08 11:34:43 changed by Bastian Kleineidam <calvin@debian.org>

I don't think hash collisions for different models have a big performance penalty (if any). You usually end up having the same type of objects in a set/list (populated from MyModel?.objects.all() or similar). The pk gives a good hash data in this case.

02/16/08 15:57:39 changed by Simon Greenhill <dev@simon.net.nz>

  • needs_better_patch set to 1.
  • stage changed from Unreviewed to Ready for checkin.

(in reply to: ↑ 2 ) 02/16/08 21:40:57 changed by Eric

Replying to Bastian Kleineidam <calvin@debian.org>:

I don't think hash collisions for different models have a big performance penalty (if any). You usually end up having the same type of objects in a set/list (populated from MyModel?.objects.all() or similar). The pk gives a good hash data in this case.

That's not entirely true when dealing with the content types framework.

02/18/08 19:47:52 changed by mtredinnick

I implemented a hash function independent of having seen this ticket and arrived at basically the same logic Bastian's using. The common case will be objects of the same type, using the pk as a hash is very fast (quite a bit faster than hashing a tuple of class and pk) and satisfies Python's requirements, and even if you do get the odd collision in the case of mixed content types, it doesn't matter that much. Simplicity wins here.

02/18/08 19:59:34 changed by mtredinnick

  • status changed from new to closed.
  • resolution set to fixed.

(In [7132]) Fixed #2936, #6500 -- Added a hash() method to Models (since we implement our own eq method).


Add/Change #6500 (Make models hashable)




Change Properties
Action