Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific fields in Django get_object_or_404

I have a model in Django with too many fields. Ex:

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?

like image 908
Arundas R Avatar asked Jan 06 '23 08:01

Arundas R


2 Answers

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

Required arguments

klass

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)
like image 155
Burhan Khalid Avatar answered Jan 08 '23 10:01

Burhan Khalid


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.

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)

Based on : https://docs.djangoproject.com/en/1.10/_modules/django/shortcuts/#get_object_or_404

like image 34
e4c5 Avatar answered Jan 08 '23 11:01

e4c5