get_object_or_404 and foreignkey

315 views
Skip to first unread message

Jamie Pittock

unread,
Mar 7, 2009, 12:42:26 PM3/7/09
to Django users
Hi,

I have an app with countries and counties. The simplified model is:

class Country(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField()

def __unicode__(self):
return self.name

class County(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField()
country = models.ForeignKey(Country)

def __unicode__(self):
return self.name

The url for a county would be of the format domain.com/country/
country/.

On the corresponding view for that url I'm currently doing this...

def view_county(request, country_slug, county_slug):
country = get_object_or_404(Country, slug=country_slug)
county = get_object_or_404(County, slug=county_slug,
country=country.id)

1. First checking to see if a country exists with that slug
2. Then checking to see if a county exists with that slug and also
with the country_id of the country found in step #1

Can that be merged into one step, or is there a better way completely
of doing it?

Jamie Pittock

unread,
Mar 7, 2009, 12:50:48 PM3/7/09
to Django users
Sorry, the correct url would be domain.com/country/county/

Daniel Roseman

unread,
Mar 7, 2009, 2:39:58 PM3/7/09
to Django users
On Mar 7, 5:42 pm, Jamie Pittock <smallb...@gmail.com> wrote:
It depends - do you actually need the 'country' object in the rest of
your view, or are you simply using it as a way to get the county? If
the latter, you could just do:
county = get_object_or_404(Country, slug=county_slug,
country__slug=country_slug)
Note the double underscore in the country__slug argument.

--
DR.

Jamie Pittock

unread,
Mar 7, 2009, 3:21:36 PM3/7/09
to Django users
Thanks Daniel. Yeah it's just a way of getting the county so I'll try
your second option. Could you possibly point me to the docs that
explain the double underscore?

On Mar 7, 7:39 pm, Daniel Roseman <roseman.dan...@googlemail.com>
wrote:

Daniel Roseman

unread,
Mar 7, 2009, 4:37:53 PM3/7/09
to Django users
On Mar 7, 8:21 pm, Jamie Pittock <smallb...@gmail.com> wrote:
> Thanks Daniel.  Yeah it's just a way of getting the county so I'll try
> your second option.  Could you possibly point me to the docs that
> explain the double underscore?

It's the standard syntax for lookups across relationships. See
http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

--
DR.

Jamie Pittock

unread,
Mar 8, 2009, 5:27:56 PM3/8/09
to Django users
Thanks again. I'm still new to all this.

On Mar 7, 9:37 pm, Daniel Roseman <roseman.dan...@googlemail.com>
wrote:
> It's the standard syntax for lookups across relationships. Seehttp://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-...
>
> --
> DR.
Reply all
Reply to author
Forward
0 new messages