#22413: Allow model instance attributes in ModelAdmin.fields
-------------------------------------+-------------------------------------
     Reporter:  moritzs              |                    Owner:  moritzs
         Type:  New feature          |                   Status:  assigned
    Component:  contrib.admin        |                  Version:  master
     Severity:  Normal               |               Resolution:
     Keywords:  ModelAdmin instance  |             Triage Stage:
  attribute field                    |  Unreviewed
    Has patch:  1                    |      Needs documentation:  0
  Needs tests:  1                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by moritzs):

 Replying to [comment:2 timshaffer@…]:
 > Forgive my ignorance (perhaps), but what's wrong with changing your code
 to this:
 >
 > {{{
 > class MyModel(models.Model):
 >     value = models.CharField(max_length=20)
 >
 >     @property
 >     def reversed_value(self):
 >         return self.value[::-1]
 > }}}
 >
 > That would not require any changes to Django code.

 My example may be a bit trivial, here is another that hopefully shows, why
 it is necessary:

 {{{
 class MyBaseModel(models.Model):
     def __getattr__(self, name):
         if name.endswith('_to_upper'):
             return getattr(self, name[:-len('_to_upper')]).upper()
         elif name.endswith('_to_lower'):
             return getattr(self, name[:-len('_to_lower')]).lower()
         else:
             return AttributeError()

     class Meta:
         abstract = True


 class MyModel(MyBaseModel):
     val1 = models.CharField(max_length=20)
     val2 = models.CharField(max_length=20)
 }}}
 Now it works like this:
 {{{
 >>> m = MyModel()
 >>> m.val1 = 'Foo'
 >>> m.val2 = 'Bar'
 >>> m.val1_to_upper
 'FOO'
 >>> m.val2_to_lower
 'bar'
 }}}
 In this particular example you could still add properties for each
 combination of val1, val2 and to_upper, to_lower, but this won't be
 possible, if `__getattr__` gets more complex.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/22413#comment:3>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/065.03e81f4f05da5c460d5f638d4b4cc526%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to