I have a Competition model which has a corresponding CompetitionEntry model. I’d like to show the number of entries for each competition in the admin view.
Here’s the model definition:
class Competition(models.Model):
def __unicode__(self):
return self.competition_name
competition_name = models.CharField(max_length=100)
competition_text = models.TextField()
active = models.BooleanField('Is this competition active?', blank=True)
date_posted = models.DateTimeField(auto_now_add=True)
class CompetitionEntry(models.Model):
def __unicode__(self):
return self.competition.competition_name
competition = models.ForeignKey(Competition)
user = models.ForeignKey(User)
date_entered = models.DateTimeField(auto_now_add=True)
is_winner = models.BooleanField('Is this entry the winner?', blank=True)
My Django skills are a little rusty, but there should be a fairly simple way to add this to the admin, right? Any pointers? I can’t quite work out how the Competition class can ‘talk’ to the CompetitionEntry class since the relationship is defined inside CompetitionEntry, but I want to show the entries inside Competition.
You can refer to python functions in a ModelAdmin by adding it to the
fieldsetsorlist_displayandreadonly_fieldsattributes.You can ‘talk’ to a reverse relationship via the reverse related managers dynamically added to each class that a foreign key points to which is, by default,
lowercasemodelname_setand behaves exactly like your defaultobjectsmanager.