LukeJenx
LukeJenx

Reputation: 63

Django get foreign key data within views.py

I am starting off with django development and I am stuck getting some values out. In my mind it should be simple.

I have multiple models but I am having difficulty getting the area (county) from the event itself in my views. Below I have a very short sample of the event code (not really relevant however, if you need more just ask).

class Event(models.Model):
    organiser = models.ForeignKey(User)
    etc...

The problem is a single event can be advertised in multiple areas (limited on the event type). To make sure it's not a many to many I have defined an event county as below:

class EventCounty(models.Model):
    county = models.ForeignKey(county)
    event = models.ForeignKey(event)

Now the problem lies in the views, for my index page I want to show the 5 recently added and the 5 upcoming events. This is really simple as I can order by the date_added and event_date fields within Event. However, I am not really sure how to access the county from this data.

I am assuming I could just write the sql statement myself (it's simple) however, if possible I would like to stay within the django framework and use their code. I believe the below statement would be something I will need to translate (it may or may not work!).

select county from EventCounty where event in (listevents);

If anybody knows how I can get this to work I will be grateful!

Thanks in advance,

Luke

Upvotes: 0

Views: 1327

Answers (4)

derstock
derstock

Reputation: 41

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.)

Upvotes: 0

Krab
Krab

Reputation: 6756

Check select_related if you want include referenced objects

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

select_related on Django doc. sites

Upvotes: 1

Sudipta
Sudipta

Reputation: 4971

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

Upvotes: 0

Rohan
Rohan

Reputation: 53326

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.

Upvotes: 0

Related Questions