On Sat, 2006-05-13 at 01:33 +0000, George Sakkis wrote:
> Is there a way to combine python properties with Django fields so that
> one can essentially use both regular (persistent) and callable fields
> transparently ? If the previous sentence didn't make any sense, here's
> a simplest example:
>
> from django.db.models import Model, IntegerField
>
> class Foo(Model):
> number = IntegerField()
> square = property(lambda self: self.number ** 2)
>
> x = Foo(number=3)
> # attribute access works transparently:
> print x.number, x.square
> # still you can't do something "for every field" and have square
> # included
> for field in Foo._meta.fields:
> print "%s: %s" % (field.name, getattr(x,field.name)
Short answer: no, but easy to simulate.
The behaviour you are seeing is really because the persistent fields are
"faked" in some sense (by being hidden and managed in _meta), rather
than because properties are behaving unnaturally. Extracting all
properties from a class is not amazingly common in Python (unless you
are writing meta-code that requires introspection), so there is no
built-in one-stop function. But you could define a function like:
def get_properties(obj):
for name, value in obj.__class__.__dict__.items():
if type(value) == type(property()):
yield name
and then "for p in get_properties(x): ..." loops over the properties. I
made it return an iterator, you might want a list returned or whatever.
But that is incidental to the problem.
Regards,
Malcolm
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---