Django: Link a field of one model to a field of another
<p>I'm working through the Tango with Django book and have decided to add some of my own functionality but have an issue.</p>

<p>I have two models, Category and Page</p>

<pre><code>class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True)

class Page(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)
</code></pre>

<p>Now what I'm trying to do is make the Category "views" field a sum of the views of all of the pages within that category</p>

<p>In my test database population script I am doing it this way:</p>

<pre><code>cats = {"Python": {"pages": python_pages,
                   "views": sum(page["views"] for page in python_pages),
                   },
        "Django": {"pages": django_pages,
                   "views": sum(page["views"] for page in django_pages),
                   },
        "Other Frameworks": {"pages": other_pages,
                             "views": sum(page["views"] for page in other_pages),
                             }
        }
</code></pre>

<p>This works for the populating the database, but how would I make it so that the category "views" updates whenever a page "views" field is changed? </p>

<p>For example if two different pages in the same category's "views" go up by one, category's "views" would go up by two?</p>

<p>I would add this to your category class instead of using the views field:</p>

<pre><code>def get_views(self):
    views=0
    for page in pages_set:
        views+=page.views
    return views
</code></pre>

python django database models