On 24 jan, 21:20, Filip Gruszczyński <grusz...@gmail.com> wrote: > > > You could write a custom descriptor then. But the whole idea of a > > class-level pseudo-constant pointing to a model instance still looks > > rather backward to me. > > What is a custom descriptor? I have never used it. Is it something > like a property?
The descriptor protocol is the mechanism that allows both property and method: http://docs.python.org/reference/datamodel.html#implementing-descriptors http://users.rcn.com/python/download/Descriptor.htm In your case, something like the following could do: class ModelInstanceConst(object): def __init__(self, **lookup): self.lookup = lookup def __get__(self, instance, cls=None): if instance is None and cls is None: # shouldn't happen but well... return self if cls is None: cls = type(instance) return cls.objects.get(**self.lookup) def __set__(self, instance, value): raise AttributeError("attribute is read-only") def __delete__(self, instance): raise AttributeError("attribute is read-only") class MyModel(models.Model): CONST = ModelInstanceConst(id=1) NB : not tested. > > Oh, and while were at it: the Python standard for the current class > > param name in a classmethod is 'cls', not 'Class' ;) > > I have seen both cls and klass in django code. I prefer mine, because > it clearly indicates, that the objects is not an instance, but a class It's still an instance (of it's metaclass). If it's a newstyle class, at least ;) > (and therefore type instance, right?). Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo: pass ... >>> isinstance(Foo, type) False >>> But anyway... > > Yes they do - as long as their metaclass derives from the appropriate > > metaclass (ModelBase IIRC but better to check it out). > > I'll definitely try that. I'm not sure it's necessary here - the custom descriptor solution might be enough. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.