views:

133

answers:

1

Hello, 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

A: 

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

piquadrat
thanks alot for taking your time !
Hellnar