leshank
leshank

Reputation: 113

Appropriate model structure for recording history of values

I can't work out what the appropriate model structure should be for this problem (simplified version to make explanation easier)

The goal is:

I know I can have a separate model for height and for weight, linking them to Person by ForeignKey but it makes the admin presentation confusing and dis-jointed by allowing multiple entries at a time.

Alternatively, can I have height and weight as fields in Person (benefit of having clean list_view and inclusion of these fields in fieldsets), and when there is any update store the previous value into a different model? This model can then be listed to show some one's history of values.

Any help is greatly appreciated.

Upvotes: 1

Views: 103

Answers (2)

krs
krs

Reputation: 4154

Use ForeignKeys to height and weight models, then add a property to access that field

class Person(model)
    name = CharField()

    @property
    def weight(self):
        return self.weighthistory.latest().value


class Weight(model):
    value = IntegerField()
    date = DateTimeField()
    person = ForeignKey(Person, related_name="weighthistory")

class Height(model)
    value = IntegerField()
    date = DateTimeField()
    person = ForeignKey(Person)

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

django-reversion provides this functionality. At each save() of your model, a history is saved with changed values and you can roll back to any previous version, in addition to listing all changes.

It does not require changing of your models, and even comes with an admin integration with a custom admin class.

A low level API provides more functionality.

Upvotes: 0

Related Questions