django: how to make an attribute of a table be count of entries in another table -


continuing django polls tutorial, want entry (i called numchoices) in poll model automatically updates number of choices associated poll. how can that?

class poll(models.model):     question = models.charfield(max_length=200)     pub_date = models.datetimefield('date published')     numchoices = models.integerfield()     def __unicode__(self):         return self.question     def was_published_recently(self):         now=timezone.now()         return now-datetime.timedelta(days=1) <= self.pub_date <     was_published_recently.admin_order_field = 'pub_date'     was_published_recently.boolean = true     was_published_recently.short_description = 'published recently?'  class choice(models.model):     poll = models.foreignkey(poll)     choice_text = models.charfield(max_length=200)     votes = models.integerfield(default=0)     def __unicode__(self):         return self.choice_text 

clarification, ideal use case such that:

if want list polls number of choices associated each poll, won't have query choice table.

but every time add choice, poll entry associated choice update it's numchoices count

you don't want that. make property of model instead.

class poll(models.model):    ...   @property   def numchoices(self):     return self.choice_set.count() 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -