Reputation: 13
I have a many-to-one relationship between organizations and events. One organization can have many events. I have a template for showing all events that everybody can see filtered by city. But I want the organization detail view to show events belonging only to a specific organization.
models.py
class Organization(models.Model):
name = models.Charfield(max_length=27)
slug = models.SlugField(max_length=25, null=True, blank=True)
[...]
def __unicode__(self):
return self.name
class Events(models.Model):
org = models.ForeignKey(Organization, on_delete=models.CASCADE, default=1)
time = models.DateTimeField(null=True, blank=True)
city = models.CharField(
max_length=25,
choices = CITY_CHOICES,
default = 'NY'
)
[...]
def __unicode__(self):
return '%s %s' % (self.org, self.time)
I use this template tag to filter events by city (NY for this one):
@register.inclusion_tag('mysite/event_list.html')
def event_ny_tag(event):
return {'events': Events.objects.filter(linn='NY')}
url.py
urlpatterns = [
url(r'^$', HomePageView.as_view(), name='home'),
url(r'^organizations/$', OrganizationList.as_view(), name='organizations'),
url(r'^events/$', EventList.as_view(), name='events'),
url(r'^(?P<slug>[-\w]+)/$', OrgDetailView.as_view(), name='org_detail'),
]
But how can I filter events only by one specific organization? There are only two cities but 20 organizations. How to do it without hardcoding it? With a slug?
This is not a copy paste. Just a sample code similar to mine.
Upvotes: 0
Views: 489
Reputation: 946
Since the events have the foreignkey Organization. You can get the list of events associated with an organization in its detail view template like this:
{% for event in organization.events_set.all %}
{{ event }}
{% endfor %}
Update: To filter according to a semester you could make use of a custom template filter that passes the semester as argument along with the event list, like this:
@register.filter
def semester(events, sem):
return events.filter(semester=sem)
and do this in the template
<!--Semester 1-->
{% for event in organization.events_set.all|semester:"sem1" %}
{{ event }}
{% endfor %}
Upvotes: 1