I am using a relational database via Django Models and have the following classes:
class EventSite(models.Model):
name = models.CharField(....etc.)
class Artist(models.Model):
jobsite = models.ForeignKey(JobSite, related_name="jobsite", null=True....etc.)
is_british = models.BooleanField(default=False)
class Concert(models.Model):
event = models.ForeignKey(EventSite, related_name="event_concert", null=True....etc.)
artists = models.ManyToManyField(Artist, related_name="artist_conerts", null=True....etc.)
So each Concert is related to an Event Site and can have several Artists. Inside of my html template, I need to get a total count of the count of the number of Artists on each Concert related to an Event. (See the pic)
So the html I tried looks something like:
{% for site in event_sites %}
{{site.event_concert.all.artists.count}},
{% endfor %}
So for my scenario, I'm hoping that will display to the user:
12,3,0
but it's just returning an empty string right now.
I cannot seem to find a solution, which I suspect is because I don't have the right terminology to describe what I'm trying to get. In some scenarios, I'll also have to count only the artists that are british. Any help would be greatly appreciated!
CodePudding user response:
I can think of doing it in two ways in views or in models. The way I would do it will be creating method in the model.
...
class EventSite(models.Model):
name = models.CharField(max_length=100)
def get_site_artists(self):
artists = 0
for concert in self.event_concert.all():
artists = concert.artists.all().count()
return artists
...
And then use it in the template like this:
{% for site in event_sites %}
{{site.get_site_artists}},
{% endfor %}