0

I am trying to make an automated database entry generation with Django, whenever I trigger it to happen.

For instance, assume I have a such model:

class status_entry(models.Model):
    name = models.TextField()
    date = models.DateField()
    status = models.BooleanField()

and I have several entries to the model such as:

1 - "bla bla" - 2009/11/6 - true
2 - "bla bla" - 2009/11/7 - true
3 - "bla bla" - 2009/11/10 - true

so as you can see between my 2nd and 3rd entry, I have 2 absent entry days (2009/11/8 and 2009/11/9), via creating some view or script I want to auto fill these absent day entries such as :

id   name        date       status 
------------------------------------
1 - "bla bla" - 2009/11/6 - true
2 - "bla bla" - 2009/11/7 - true
3 - "bla bla" - 2009/11/8 - false
4 - "bla bla" - 2009/11/9 - false
5 - "bla bla" - 2009/11/10 - true

Thanks

skaffman
  • 398,947
  • 96
  • 818
  • 769
Hellnar
  • 62,315
  • 79
  • 204
  • 279
  • So what exactly is the problem? Where are you having trouble? – Daniel Roseman Aug 16 '09 at 17:24
  • What's the specification? If you have the 6th and 7th in your DB and you subsequently ad the 10th, you'd like the 8th and 9th to be backfilled (but with different values)? Sounds like a database trigger, not a Django problem. – hughdbrown Aug 16 '09 at 17:28
  • The trouble is the decision of how to implement my idea of auto generation of these table rows :) It's my first time facing a such problem and that's why what method would be more clever (by django or through some DB trigger) – Hellnar Aug 16 '09 at 17:34

1 Answers1

0

You can overwrite save and do the autofill there (daterange function taken from here):

from datetime import timedelta

def daterange(start_date, end_date):
    for n in range((end_date - start_date).days):
        yield start_date + timedelta(n)


class StatusEntry(models.Model):
    name = models.TextField()
    date = models.DateField()
    status = models.BooleanField()

    def __unicode__(self):
        return "%s - %s - %s" % (self.name, unicode(self.status), unicode(self.date))

    def save(self, fill=True):
        if fill and not self.id: # autofill on insert, not on update
            newest = StatusEntry.objects.all().order_by("-date")[:1]
            if newest and newest[0].date < self.date:
                for date in daterange(newest[0].date + timedelta(1), self.date):
                    entry = StatusEntry(name=self.name, date=date, status=False)
                    entry.save(fill=False)
        super(StatusEntry, self).save()

You could also use signals or do it with triggers, like hughdbrown suggested

Community
  • 1
  • 1
Benjamin Wohlwend
  • 30,958
  • 11
  • 90
  • 100