2

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?

O. Davis
  • 45
  • 1
  • 5

2 Answers2

2

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

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.

Danil
  • 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
  • @Chiefir were you able to check this solution? Did it work for you? – Danil Jan 09 '19 at 09:40
  • 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