views:

268

answers:

1

I have a model:

class Person (models.Model):
    name     = models.CharField ()
    birthday = models.DateField ()
    age      = models.IntegerField ()

I want to make age field to behave like a property:

    def get_age (self):
        return (datetime.datetime.now() - self.birthday).days // 365

    age = property (get_age)

but at the same time I need age to be a true field, so I can find it in Person._meta.fields, and assign attributes to it: age.help_text = "Age of the person", etc.

Obviously I cannot just override Person.save() method to calculate and store age in the database, because it inevitably will become wrong later (in fact, it shouldn't be stored in the database at all).

Actually, I don't need to have setters now, but a nice solution must have setting feature.

Is it possible in Django, or probably there is a more pythonic and djangoic approach to my problem?

+1  A: 

you're going about it in a strange way. you only need to store the birthday (which you're already doing).

if you need to do queries based on age, take in the age, and then search on the birthdays that fit the requirements.

#get people over 50
age = 50 #in years
age_ago = datetime.now - age #use timedelta i don't know the syntax off the top of my head
Person.objects.filter(birthday__lte=age_ago) #people whose birthday is before fifty years ago

you said it yourself "[age] shouldn't be stored in the database at all"

you're right. there is no reason to have the age field... just the property will be fine.

Brandon H
I have an automated admin-like app, which uses fields to display and edit information about objects in a unified way. Without the feature I'm looking for, I have to treat such properties in a specific way, storing and processing labels (verbose_name), help_texts etc. separately. That's awkward and messy.
Anatoly Rr
you shouldn't have to edit `age` only `birthday`. No matter what `birthday` is `age` will always be a function of `birthday` (i.e. now - birthday). that's why i can't understand what you're trying to say.
Brandon H
I have a class: `class PersonReportPrinter(ReportPrinter)` with fields `model = Person` and `columns = ('id', 'name', 'age')` and the class uses `Person._meta.get_field_by_name` to get `verbose_name` and `help_text`. Actually, the real application is somewhat more complex, there is a number of models and several helping classes, so workarounds are too annoying.
Anatoly Rr