Arundas R Arundas R - 1 year ago 127
Python Question

Select specific fields in Django get_object_or_404

I have a model in Django with too many fields.

class MyModel(models.Model):
param_1 = models.CharField(max_length=100)
param_25 = models.CharField(max_length=100)

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

obj = MyModel.objects.get(pk=5)
obj = MyModel.objects.filter(pk=5)[0]
obj = get_object_or_404(MyModel, pk=1)

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,

SELECT "param_1" FROM mymodel WHERE pk=1

How can this be done using get_object_or_404?

Can some one help to find a solution for this?

Answer Source

The first argument to get_object_or_404 can be a Model, a Manager or a QuerySet:

Required arguments


A Model class, a Manager, or a QuerySet instance from which to get the object.

So, all you have to do is pass in a pre-filtered QuerySet, such as the one returned by only:

obj = get_object_or_404(MyModel.objects.only('param_1', 'param_2'), pk=1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download