Skip to content

Instantly share code, notes, and snippets.

@jscn
Created July 18, 2012 11:28
Show Gist options
  • Save jscn/3135697 to your computer and use it in GitHub Desktop.
Save jscn/3135697 to your computer and use it in GitHub Desktop.
Django Models and the ==, 'in' and 'is' operators
def __eq__(self, other):
return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()
$ python manage.py shell
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from project.app.models import Animal
>>> cat = Animal(species="feline")
>>> dog = Animal(species="canine")
>>> cat.species == dog.species
False
>>> cat is dog
False
>>> # A cat is not a dog. Duh.
>>> # However...
>>> cat in [dog]
True
>>> # Oh no! How did the cat get in the dog? Wait a minute...
>>> cat == dog
True
>>> # What?!
>>>
>>> # Private keys don't exist.
>>> cat.pk is None
True
>>> dog.pk is None
True
>>> # Saving generates the private key.
>>> cat.save()
>>> cat.pk
2
>>> # == and in operators now work as expected.
>>> cat == dog
False
>>> cat in [dog]
False
>>>
from django.db import models
class Animal(models.Model):
species = models.CharField(max_length=100)
$ python
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Animal():
... def __init__(self, species):
... self.species = species
...
>>> cat = Animal(species="feline")
>>> dog = Animal(species="canine")
>>> cat.species == dog.species
False
>>> cat is dog
False
>>> cat in [dog]
False
>>> cat == dog
False
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment