Is it possible to replace values ina queryset before sending it to your template?

Posted by Issy on Stack Overflow See other posts from Stack Overflow or by Issy
Published on 2010-04-23T20:13:22Z Indexed on 2010/04/23 20:43 UTC
Read the original article Hit count: 271

Hi Guys,

Wondering if it's possible to change a value returned from a queryset before sending it off to the template. Say for example you have a bunch of records

Date | Time | Description
10/05/2010 | 13:30 | Testing...

etc...

However, based on the day of the week the time may change. However this is static. For example on a monday the time is ALWAYS 15:00.

Now you could add another table to configure special cases but to me it seems overkill, as this is a rule. How would you replace that value before sending it to the template?

I thought about using the new if tags (if day=1), but this is more of business logic rather then presentation.

Tested this in a custom template tag

def render(self, context):
    result = self.model._default_manager.filter(from_date__lte=self.now).filter(to_date__gte=self.now)
    if self.day == 4:
        result = result.exclude(type__exact=2).order_by('time')
    else:
        result = result.order_by('type')
    result[0].time = '23:23:23'
    context[self.varname] = result
    return ''

However it still displays the results from the DB, is this some how related to 'lazy' evaluation of templates?

Thanks!

Update Responding to comments below: It's not stored wrong in the DB, its stored Correctly However there is a small side case where the value needs to change.

So for example I have a From Date & To date, my query checks if todays date is between those. Now with this they could setup a from date - to date for an entire year, and the special cases (like mondays as an example) is taken care off. However if you want to store in the DB you would have to capture several more records to cater for the side case. I.e you would be capturing the same information just to cater for that 1 day when the time changes. (And the time always changes on the same day, and is always the same)

© Stack Overflow or respective owner

Related posts about django-models

Related posts about django