[Answer]-Django get foreign key data within views.py

1👍

Check select_related if you want include referenced objects

EventCounty.objects.select_related('event').filter(....)

select_related on Django doc. sites

👤Krab

0👍

As you defined a event can be in multiple counties. So event object has set of County you can access them as

event_obj.county_set.all()

county_set() is RelatedManager so you can do .filter(), .get() etc on it.

👤Rohan

0👍

objs = EventCounty.objects.filter(event__in=listevents)
countyList = []
for obj in objs:
    countyList.append(obj.county)

0👍

As the EventCount model holds a ForeignKey to Event model it is rather simple – ForeignKey enables “backward” relation (see Django documentation). In your case this could look like:

events = Event.objects.all().order_by(<put your date field here>)[:5]

To get a list (or QuerySet) off all EventCounty objects for e.g. first Event object just use:

events_county = events[0].eventcounty_set.all()

As suggested by Rohan the eventcounty_set is a RelatedManager which means you can work with it like with a QuerySet (filter, exclude, order, slice etc.)

Leave a comment