On 7 déc, 11:45, Thomas Guettler <h...@tbz-pariv.de> wrote:
> Hi,
>
> I have this code:
>
> from django.contrib.auth.models import Group
>
> class MyModel(models.Model):
>     default_group=Group.objects.get(name='MyGroup')
>
> This worked, since I added the Model after the group MyGroup
> was created. But it breaks syncdb.

Indeed.

> I need this on the class, using a property does not work, since
> AFAIK properties only work for instances.

The property builtin type only "works" for instances, yes, but well,
the property type is just one possible application of the descriptor
protocol - FWIW, the function type implements the descriptor protocol
too (that's how functions become methods), and Django's models
relationships are also implemented using custom descriptors. Oh, and
yes : a descriptor's __get__ method is always called, whether it's
looked up on a class or instance (else classmethods or unboundmethods
wouldn't work). So one possible solution could be to write your own
custom descriptor:

class DefaultModelAttribute(object):
    def __init__(self, lookup_method, **lookup_args):
        self._lookup_method = lookup_method
        self._lookup_args = lookup_args
    def __get__(self, instance, cls=None):
        return self._lookup_method(**self._lookup_args)
    def __set__(self, instance, value):
        raise AttributeError("read-only, sorry")


class MyModel(models.Model):
    default_group=DefaultModelAttribute(Group.objects.get,
name='MyGroup')

NB : untested code, so according to Murphy's law it should of course
break on first test with a very obvious (or very obscure...) error !-)


Now I'm not sure it's the right thing to do - depending on how you
expect this to be used, it may or not work correctly, and even then it
might as well be pure overkill. So if may ask: do you really need to
have a computed attribute here ? How do you use this attribute
exactly ?


--

You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@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.


Reply via email to