Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am sharing a viewset between two types of routes in Django: one is a nested route (/users/:id/comments/:id/), and a regular route (/comments/:id/). The query set returned is either filtered by the user_pk or it's not. What is an idiomatic way of writing the following?

if(user_pk):
    queryset = Comment.objects.filter(pk=pk, user=user_pk)
else:
    queryset = Comment.objects.filter(pk=pk)
share|improve this question
up vote 2 down vote accepted

It's fine.
As this function doesn't have a default value for parameters, you would have to use a dictionary if you want to make it more DRY. I'd do something like:

kwargs = {
    'pk': pk,
    'user': user_pk
}
if not kwargs['user']:
    del kwargs['user']
queryset = Comment.objects.filter(**kwargs)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.