Search code examples
pythondjangomethodsextend

Extending get_object_or_404 to use select_related


What i am trying to do is to define a custom method that uses django.shortcuts.get_object_or_404 and select_related. I have the method defined as follows:

models.py

class Sample(models.Model):
    slug = models.SlugField()
    # Sample class fields

helpers.py

import models
from django.shortcuts import get_object_or_404

def get_sample_or_404(**kwargs):
    sample = get_object_or_404(models.Sample.objects.select_related(), kwargs)
    return sample

Now, whenever i try to use this method, i get get_sample() got an unexpected keyword argument 'xxxx'. Following is how i am using it:

sample = get_sample_or_404(slug='first-sample')

Could anybody put me in the right direction ?

Thanks.


Solution

  • The kwargs must be expanded:

    sample = get_object_or_404(models.Sample.objects.select_related(), **kwargs)