python - Django: Link a field of one model to a field of another -
i'm working through tango django book , have decided add of own functionality have issue.
i have 2 models, category , page
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)
now i'm trying make category "views" field sum of views of of pages within category
in test database population script doing way:
cats = {"python": {"pages": python_pages, "views": sum(page["views"] page in python_pages), }, "django": {"pages": django_pages, "views": sum(page["views"] page in django_pages), }, "other frameworks": {"pages": other_pages, "views": sum(page["views"] page in other_pages), } }
this works populating database, how make category "views" updates whenever page "views" field changed?
for example if 2 different pages in same category's "views" go one, category's "views" go two?
i add category class instead of using views field:
def get_views(self): views=0 page in pages_set: views+=page.views return views
Comments
Post a Comment