On Aug 24, 6:12 pm, Ken <ken.w.sm...@gmail.com> wrote:
> Apologies if this is in an FAQ somewhere, but I've been unable to find
> it...
>
> As a complete newcomer to Django (and Python, for that matter), I'd
> like to present my users with an HTML table that contains columns a, b
> and c from my table in the database, and then do arithmetic on the
> Model columns before presenting the user with the result (e.g the user
> sees a, b+c --- or a, int(b/c)).
>
> I know that I can't do the arithmetic with template tags.
>
> I can very easily create an SQL database view to do this, and then
> create a corresponding Django model.  Is there a way I can do this in
> directly Django using a Django view or model?  E.g. by presenting a
> custom column to represent the results of arithmetic on one or more
> other model columns.
>
> I'd eventually like to be able to call some custom mathematical
> functions that are not (easily) available in by DB.
>
> Thanks in advance.

You can define a custom method on your model class, and call that for
each row in your queryset. For added ease of use, you can make the
method a property, so you refer to it just like any other field
(except you can't set it).

class MyModel(models.Model):
    a = models.IntegerField()
    b = models.IntegerField()

    @property
    def c(self):
        return self.a + self.b

and in your template:

<tr><td>A</td><td>B</td><td>A+B</td></tr>
{% for row in rows %}
<tr><td>{{ row.a }}</td><td>{{ row.b }}</td><td>{{ row.c }}</td></tr>
{% endfor %}
--
DR.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to