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 <code>get_object_or_404</code> can be <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#django.shortcuts.get_object_or_404" rel="nofollow">a Model, a Manager or a QuerySet</a>:</p>

<blockquote>
  <p>Required arguments</p>
  
  <p><strong>klass</strong></p>
  
  <p>A Model class, a Manager, or a QuerySet instance from which to
  get the object.</p>
</blockquote>

<p>So, all you have to do is pass in a pre-filtered QuerySet, such as the one returned by <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#only" rel="nofollow"><code>only</code></a>:</p>

<pre><code>obj = get_object_or_404(MyModel.objects.only('param_1', 'param_2'), pk=1)
</code></pre>

python sql django model