On Sun, Aug 21, 2016 at 4:56 AM, ludovic coues <cou...@gmail.com> wrote:
> You need to check somewhere that the category exist and that your item > belong to the category. > The get object method seems like a good place to do it. Something like > that should do the trick > > def get_object(self, queryset=None): > """ Return a 404 code if > * no link with given slug/id > * no category with given slug > * link isn't part of the right category > """" > link = get_object_or_404(Link, > pk=self.kwargs['pk'],slug=self.kwargs['slug']) > category = get_object_or_404(Category, > slug=self.kwargs['category']) > if not category in link.category_set: > raise Http404 > return link > > This works (using link.category instead of link.category_set), but it is inefficient (both in lines of code and SQL queries). You're using multiple queries to validate the existence of a single object. The raise statement is also unneeded. I would suggest this: def get_object(self, queryset=None): """Retrieve the object using the given PK, link slug, and category slug."""" link = get_object_or_404(Link, pk=self.kwargs['pk'], slug= self.kwargs['slug'], category__slug=self.kwargs['category']) return link Here, we validate the category slug (well, all of the captured URL values) using a JOIN between the Link and Category models, rather than running separate queries and comparing the results in Python. There is also no need to 'raise Http404' because that's the point of get_object_or_404() if the object is not found (ie one of the 3 pieces of information we were given doesn't line up). Personally I always name my URL capture arguments with a suffix such as _pk or _slug (ie category_slug) to make it a bit more clear as to what is being captured, but that's a personal preference. -James -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWj6RPWw0Hh78hWhNgz-kUZC%2Bow%3DLAqwU6FNTBbcUrzTw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.