better Resource.get_model and Resource.get_queryset methods (directly inspired from generic.DetailView)

This commit is contained in:
Sébastien Piquemal 2012-01-09 20:05:55 +02:00
parent 3a52c213f9
commit 89e1cae28e

View File

@ -1,6 +1,7 @@
from django import forms from django import forms
from django.core.urlresolvers import reverse, get_urlconf, get_resolver, NoReverseMatch from django.core.urlresolvers import reverse, get_urlconf, get_resolver, NoReverseMatch
from django.db import models from django.db import models
from django.core.exceptions import ImproperlyConfigured
from djangorestframework.response import ErrorResponse from djangorestframework.response import ErrorResponse
from djangorestframework.serializer import Serializer, _SkipField from djangorestframework.serializer import Serializer, _SkipField
@ -529,18 +530,36 @@ class ModelResource(FormResource):
def get_model(self): def get_model(self):
""" """
Return the model class for this view. Return the model class for this resource.
""" """
return getattr(self, 'model', getattr(self.view, 'model', None)) model = getattr(self, 'model', None)
if model is None:
model = getattr(self.view, 'model', None)
if model is None:
raise ImproperlyConfigured(u"%(cls)s is missing a model. Define "
u"%(cls)s.model." % {
'cls': self.__class__
})
return model
def get_queryset(self): def get_queryset(self):
""" """
Return the queryset that should be used when retrieving or listing Return the queryset that should be used when retrieving or listing
instances. instances.
""" """
return getattr(self, 'queryset', queryset = getattr(self, 'queryset', None)
getattr(self.view, 'queryset', if queryset is None:
self.get_model().objects.all())) queryset = getattr(self.view, 'queryset', None)
if queryset is None:
try:
model = self.get_model()
except ImproperlyConfigured:
raise ImproperlyConfigured(u"%(cls)s is missing a queryset. Define "
u"%(cls)s.model or %(cls)s.queryset." % {
'cls': self.__class__
})
queryset = model._default_manager.all()
return queryset._clone()
def get_ordering(self): def get_ordering(self):
""" """