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=10
Solution 1:
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)
Solution 2:
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.
defget_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__ ifisinstance(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
Post a Comment for "Select Specific Fields In Django Get_object_or_404"