def test_identifier(self): """ Ensure that get_identifier is consistent when given a single object using different parameter types. """ results = set() # This is what get_identifier should return in each case. identifier = 'auth.user.1' results.add(identifier) # Call with a pre-created identifier. results.add(get_identifier(identifier)) # Call with the Model and object_pk results.add(get_identifier(User, 1)) # Call with the content type and pk user_content_type = ContentType.objects.get_for_model(User) results.add(get_identifier(user_content_type, 1)) # Call with a model instance. results.add(get_identifier(User.objects.get(pk=1))) self.assertEqual(len(results), 1, 'Inconsistent results from get_identifier: %s' % list(results))
def test_pickle(self): """Test that you can pickle and unpickle LazyModel instances.""" gallery = PhotoGallery.objects.order_by('-id')[0] # Check all ways of creating them. lazy_galleries = ( LazyModel(gallery), LazyModel(get_identifier(gallery)), LazyModel(PhotoGallery, gallery.pk), LazyModel(PhotoGallery, slug=gallery.slug), ) for lazy_gallery in lazy_galleries: pickled = pickle.dumps(lazy_gallery) unpickled = pickle.loads(pickled) self.assertEqual( gallery.get_absolute_url(), unpickled.get_absolute_url(), ) # Check that invalid instances can still be pickled. broken_gallery = LazyModel(PhotoGallery, gallery.pk + 10000000) pickled = pickle.dumps(broken_gallery) unpickled = pickle.loads(pickled) self.assertEqual( broken_gallery.object_pk, unpickled.object_pk, )
def _get_identifier(self): """Get the identifier string for the represented object.""" if '_identifier' not in self.__dict__: object_or_string, args, kwargs = self._init_args # Get the identifier for the wrapped object, e.g. 'auth.user.1234' # If there is a lookup in the kwargs, then the following call # will figure out the object_pk. It caches these lookups. self.__dict__['_identifier'] = get_identifier(object_or_string, *args, **kwargs) return self.__dict__['_identifier']
def _get_identifier(self): """Get the identifier string for the represented object.""" if '_identifier' not in self.__dict__: object_or_string, args, kwargs = self._init_args # Get the identifier for the wrapped object, e.g. 'auth.user.1234' # If there is a lookup in the kwargs, then the following call # will figure out the object_pk. It caches these lookups. self.__dict__['_identifier'] = get_identifier( object_or_string, *args, **kwargs) return self.__dict__['_identifier']
def get_identifier(cls, *args, **kwargs): if args and type(args[0]) is cls: # Handle instances of this class differently. object_or_string, args, kwargs = args[0]._init_args args = [object_or_string] + list(args) return get_identifier(*args, **kwargs)