I am new to Django and am trying to figure out how to store historical data and be able to reference any data point from a date in the past. Say I want to store data on a kids height change as he grows and be able to compare his height at day 400 to his height at day 6xx. How would I set this up in Django? Would there need to be a foreign key relationship between height and the kid?
-
This is basic relational database modelling, nothing Python nor Django specific. – bruno desthuilliers Dec 27 '18 at 14:57
2 Answers
Forget about Django's ORM (which is really just a very thin wrapper over your SQL database) and think in terms of relational database. Here you obviously have two entities: "kid" and "height". You also have the following relationships: a "kid" has zero, one or many "height", a "height" belongs to one single "kid". This indeed translates to a "kid" table kid(+id, name, dob, ...)
and a "height" table with a foreign key on kid
: height(+id, kid_id, date, value)
.
How to write this using Django's orm is quite straighforward so I'll leave it to you.

- 75,974
- 6
- 88
- 118
You can use simple history app.
According to the docs you need to add a HistoricalRecords
field to your model:
from django.db import models
from simple_history.models import HistoricalRecords
class Kid(models.Model):
id = models.IntegerField(primary_key=True)
height = models.IntegerField()
history = HistoricalRecords()
And then all model changes will be stored in the separate table. You can use this field in the code or use admin views to check historical records and retrieve.

- 4,781
- 1
- 35
- 50
-
I have a question about that lib - when you `.save()` the instance of the model - it saves the whole instance in the `HistoricalRecords` or just the time of its last update? You can get the previous version of this instance before update via HR? It is not clearly written in the docs. – Chiefir Dec 28 '18 at 09:40
-
@Chiefir yes it saves the whole instance and can be [retrieved](https://django-simple-history.readthedocs.io/en/stable/usage.html?highlight=retrieve#reverting-the-model). – Danil Dec 28 '18 at 15:29
-
-
I did not test this solution, was just curious how this lib works. May be will use it in future if I need this functionality :) – Chiefir Jan 11 '19 at 08:24