On Mon, Feb 23, 2009 at 7:33 PM, Malcolm Tredinnick <
malc...@pointy-stick.com> wrote:

>
> On Mon, 2009-02-23 at 16:21 -0800, bendavis78 wrote:
> > I have products within categories.  The url for a product is   /store/
> > category-slug/product-slug.  My question is about the best way to get
> > the url for this product while looping through a product listing
> > page.  My view simply defines a context variable called products,
> > assigned to the results of a .filter() call.
> >
> > Given these models:
> >
> > def Category(models.Model):
> >     name = models.CharField(max_length=255)
> >     slug = models.SlugField()
> >
> > def Product(models.Model):
> >     name = models.CharField(max_length=255)
> >     slug = models.SlugField()
> >     category = models.ForeignKey(Category)
> >
> >     def get_absolute_url(self):
> >         category_slug = Category.objects.get(id=self.category_id).slug
> >         return "/%s/%s" % (category_slug, self.slug)
> >
> >
> > You can see that calling get_absolute_url()  while looping through a
> > list of products in a template will require an extra query to be sent
> > to the server for each iteration of a product,  which is clearly not
> > ideal.   My other option to use  .values() in the view to select out
> > the category slug along with all the other columns on the product,
> > but this doesn't seem ideal either.
>
> You can certainly simplify get_absolute_url() a bit:
>
>        def get_absolute_url(self):
>            category_slug = self.category__slug
>            return "/%s/%s" % (category_slug, self.slug)
>
> In this way, if it needs to, Django will look up the related model.
> However, if you've retrieved a queryset using select_related(), the
> Category instances will already be present and no extra query will be
> involved. If you're doing a loop and needing get_absolute_url, you then
> have to remember to always use select_related().
>
> You could even make that automatic by creating a custom default manager
> whose get_query_set() method looked like this:
>
>        def get_query_set(self):
>           return super(MyManager,
>        self).get_query_set().select_related()
>
> and it would always happen.
>
> Regards,
> Malcolm
>
>
>
> >
>
Malcolm,  I think it's a little early.

self.category__slug? ;) That's self.category.slug unless I've missed
something enormous.

Alex

-- 
"I disapprove of what you say, but I will defend to the death your right to
say it." --Voltaire
"The people's good is the highest law."--Cicero

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to