Select specific fields in Django get_object_or_404
<p>I have a model in Django with too many fields.
Ex:</p>

<pre><code>class MyModel(models.Model):
    param_1 = models.CharField(max_length=100)
    ...
    param_25 = models.CharField(max_length=100)
</code></pre>

<p>Now I need to get the detail view based on an id. I have seen may methods like,</p>

<pre><code>obj = MyModel.objects.get(pk=5)
obj = MyModel.objects.filter(pk=5)[0]
obj = get_object_or_404(MyModel, pk=1)
</code></pre>

<p>The last method suits the best as I can provide a 404 error without any code change. But I need only param_1 and param_2. Hence I need a query similar to,</p>

<pre><code>SELECT "param_1" FROM mymodel WHERE pk=1
</code></pre>

<p>How can this be done using get_object_or_404?</p>

<p>Can some one help to find a solution for this?</p>

<p>The first argument to is the class name of the model and all other arguments are parameters that will be passed to get. So it cannot be used here, but it's quite simple to mimic it's functionality. </p>

<pre><code>def get_object_or_404_custom(klass,fields = None, *args, **kwargs):
    queryset = _get_queryset(klass)
    try:
        if fields:
            queryset = queryset.only(*fields)
        return queryset.get(*args, **kwargs)
    except AttributeError:
        klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__
        raise ValueError(
            "First argument to get_object_or_404() must be a Model, Manager, "
            "or QuerySet, not '%s'." % klass__name
        )
    except queryset.model.DoesNotExist:
        raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
</code></pre>

<p>Based on : <a href="https://docs.djangoproject.com/en/1.10/_modules/django/shortcuts/#get_object_or_404" rel="nofollow">https://docs.djangoproject.com/en/1.10/_modules/django/shortcuts/#get_object_or_404</a></p>

python sql django model