magic-removal: Fixed #1300 -- Converted various Django code to use the new descriptor-fields DB API. Thanks much, Esaj

git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@2211 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2006-01-31 23:42:58 +00:00
parent 671da7036f
commit a06b44bdc4
19 changed files with 32 additions and 33 deletions

View File

@ -56,7 +56,7 @@ class RelatedFilterSpec(FilterSpec):
self.lookup_title = f.verbose_name
self.lookup_kwarg = '%s__%s__exact' % (f.name, f.rel.to._meta.pk.name)
self.lookup_val = request.GET.get(self.lookup_kwarg, None)
self.lookup_choices = f.rel.to._default_manager.get_list()
self.lookup_choices = f.rel.to._default_manager.all()
def has_output(self):
return len(self.lookup_choices) > 1

View File

@ -13,8 +13,7 @@ class AdminLogNode(template.Node):
def render(self, context):
if self.user is not None and not self.user.isdigit():
self.user = context[self.user].id
context[self.varname] = LogEntry.objects.get_list(user__id__exact=self.user,
limit=self.limit, select_related=True)
context[self.varname] = LogEntry.objects.filter(user__id__exact=self.user).select_related()[:self.limit]
return ''
class DoGetAdminLog:

View File

@ -71,13 +71,13 @@ def staff_member_required(view_func):
# Check the password.
username = request.POST.get('username', '')
try:
user = User.objects.get_object(username__exact=username, is_staff__exact=True)
user = User.objects.get(username=username, is_staff=True)
except User.DoesNotExist:
message = ERROR_MESSAGE
if '@' in username:
# Mistakenly entered e-mail address instead of username? Look it up.
try:
user = User.objects.get_object(email__exact=username)
user = User.objects.get(email=username)
except User.DoesNotExist:
message = _("Usernames cannot contain the '@' character.")
else:

View File

@ -103,7 +103,7 @@ def view_index(request):
'name': func.__name__,
'module': func.__module__,
'site_id': settings_mod.SITE_ID,
'site': Site.objects.get_object(pk=settings_mod.SITE_ID),
'site': Site.objects.get(pk=settings_mod.SITE_ID),
'url': simplify_regex(regex),
})
return render_to_response('admin_doc/view_index', {'views': views}, context_instance=RequestContext(request))
@ -206,7 +206,7 @@ def template_detail(request, template):
'exists': os.path.exists(template_file),
'contents': lambda: os.path.exists(template_file) and open(template_file).read() or '',
'site_id': settings_mod.SITE_ID,
'site': Site.objects.get_object(pk=settings_mod.SITE_ID),
'site': Site.objects.get(pk=settings_mod.SITE_ID),
'order': list(settings_mod.TEMPLATE_DIRS).index(dir),
})
return render_to_response('admin_doc/template_detail', {

View File

@ -21,13 +21,13 @@ def authenhandler(req, **kwargs):
superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off"))
# check that the username is valid
kwargs = {'username__exact': req.user, 'is_active__exact': True}
kwargs = {'username': req.user, 'is_active': True}
if staff_only:
kwargs['is_staff__exact'] = True
kwargs['is_staff'] = True
if superuser_only:
kwargs['is_superuser__exact'] = True
kwargs['is_superuser'] = True
try:
user = User.objects.get_object(**kwargs)
user = User.objects.get(**kwargs)
except User.DoesNotExist:
return apache.HTTP_UNAUTHORIZED

View File

@ -183,7 +183,7 @@ class User(models.Model):
def get_and_delete_messages(self):
messages = []
for m in self.get_message_list():
for m in self.message_set.all():
messages.append(m.message)
m.delete()
return messages
@ -205,11 +205,11 @@ class User(models.Model):
try:
app, mod = settings.AUTH_PROFILE_MODULE.split('.')
module = __import__('ellington.%s.apps.%s' % (app, mod), [], [], [''])
self._profile_cache = module.get_object(user_id=self.id)
self._profile_cache = module.get(user_id=self.id)
except ImportError:
try:
module = __import__('django.models.%s' % settings.AUTH_PROFILE_MODULE, [], [], [''])
self._profile_cache = module.get_object(user__id__exact=self.id)
self._profile_cache = module.get(user__id__exact=self.id)
except ImportError:
raise SiteProfileNotAvailable
return self._profile_cache

View File

@ -8,14 +8,14 @@ class RedirectFallbackMiddleware:
return response # No need to check for a redirect for non-404 responses.
path = request.get_full_path()
try:
r = Redirect.objects.get_object(site__id__exact=settings.SITE_ID, old_path__exact=path)
r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path)
except Redirect.DoesNotExist:
r = None
if r is None and settings.APPEND_SLASH:
# Try removing the trailing slash.
try:
r = Redirect.objects.get_object(site__id__exact=settings.SITE_ID,
old_path__exact=path[:path.rfind('/')]+path[path.rfind('/')+1:])
r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
except Redirect.DoesNotExist:
pass
if r is not None:

View File

@ -46,7 +46,7 @@ class SessionWrapper(object):
self._session_cache = {}
else:
try:
s = Session.objects.get_object(session_key__exact=self.session_key,
s = Session.objects.get(session_key=self.session_key,
expire_date__gt=datetime.datetime.now())
self._session_cache = s.get_decoded()
except Session.DoesNotExist:

View File

@ -18,13 +18,13 @@ class SessionManager(models.Manager):
while 1:
session_key = md5.new(str(random.randint(0, sys.maxint - 1)) + str(random.randint(0, sys.maxint - 1)) + settings.SECRET_KEY).hexdigest()
try:
self.get_object(session_key__exact=session_key)
except self.klass.DoesNotExist:
self.get(session_key=session_key)
except self.model.DoesNotExist:
break
return session_key
def save(self, session_key, session_dict, expire_date):
s = self.klass(session_key, self.encode(session_dict), expire_date)
s = self.model(session_key, self.encode(session_dict), expire_date)
if session_dict:
s.save()
else:

View File

@ -4,7 +4,7 @@ from django.utils.translation import gettext_lazy as _
class SiteManager(models.Manager):
def get_current(self):
from django.conf import settings
return self.get_object(pk=settings.SITE_ID)
return self.get(pk=settings.SITE_ID)
class Site(models.Model):
domain = models.CharField(_('domain name'), maxlength=100)

View File

@ -105,7 +105,7 @@ class ModPythonRequest(http.HttpRequest):
user_id = self.session[SESSION_KEY]
if not user_id:
raise ValueError
self._user = User.objects.get_object(pk=user_id)
self._user = User.objects.get(pk=user_id)
except (AttributeError, KeyError, ValueError, User.DoesNotExist):
from django.parts.auth import anonymoususers
self._user = anonymoususers.AnonymousUser()

View File

@ -126,7 +126,7 @@ class WSGIRequest(http.HttpRequest):
user_id = self.session[SESSION_KEY]
if not user_id:
raise ValueError
self._user = User.objects.get_object(pk=user_id)
self._user = User.objects.get(pk=user_id)
except (AttributeError, KeyError, ValueError, User.DoesNotExist):
from django.parts.auth import anonymoususers
self._user = anonymoususers.AnonymousUser()

View File

@ -559,12 +559,12 @@ def installperms(app):
num_added = 0
app_models = get_models(app)
app_label = app_models[0]._meta.app_label
package = Package.objects.get_object(pk=app_label)
package = Package.objects.get(pk=app_label)
for klass in app_models:
opts = klass._meta
for codename, name in _get_all_permissions(opts):
try:
Permission.objects.get_object(name__exact=name, codename__exact=codename, package__label__exact=package.label)
Permission.objects.get(name=name, codename=codename, package__label__exact=package.label)
except Permission.DoesNotExist:
p = Permission(name=name, package=package, codename=codename)
p.save()
@ -644,7 +644,7 @@ def createsuperuser(username=None, email=None, password=None):
sys.stderr.write("Error: That username is invalid.\n")
username = None
try:
User.objects.get_object(username__exact=username)
User.objects.get(username=username)
except User.DoesNotExist:
break
else:

View File

@ -16,7 +16,7 @@ class ObjectPaginator:
Finally, check if a page number has a next/prev page using
has_next_page(page_number) and has_previous_page(page_number).
"""
def __init__(self, manager_or_model, args, num_per_page, count_method='get_count', list_method='get_list'):
def __init__(self, manager_or_model, args, num_per_page, count_method='count', list_method='all'):
if hasattr(manager_or_model, '_default_manager'):
manager = manager_or_model._default_manager
else:

View File

@ -256,7 +256,7 @@ class Field(object):
return first_choice + list(self.choices)
rel_model = self.rel.to
return first_choice + [(x._get_pk_val(), str(x))
for x in rel_model._default_manager.get_list(**rel_model._meta.limit_choices_to)]
for x in rel_model._default_manager.filter(**rel_model._meta.limit_choices_to)]
def get_choices_default(self):
if self.radio_admin:

View File

@ -250,7 +250,7 @@ class AutomaticChangeManipulator(AutomaticManipulator):
def __init__(self, obj_key, follow=None):
self.obj_key = obj_key
try:
self.original_object = self.manager.get_object(pk=obj_key)
self.original_object = self.manager.get(pk=obj_key)
except ObjectDoesNotExist:
# If the object doesn't exist, this might be a manipulator for a
# one-to-one related object that hasn't created its subobject yet.

View File

@ -87,7 +87,7 @@ class Options:
"Returns the content-type ID for this object type."
if not hasattr(self, '_content_type_id'):
from django.contrib.contenttypes.models import ContentType
self._content_type_id = ContentType.objects.get_object(
self._content_type_id = ContentType.objects.get(
python_module_name__exact=self.module_name,
package__label__exact=self.app_label).id
return self._content_type_id

View File

@ -29,7 +29,7 @@ class AuthenticationForm(forms.Manipulator):
def isValidUser(self, field_data, all_data):
try:
self.user_cache = User.objects.get_object(username__exact=field_data)
self.user_cache = User.objects.get(username=field_data)
except User.DoesNotExist:
raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")

View File

@ -12,7 +12,7 @@ load_and_render = render_to_response # For backwards compatibility.
def get_object_or_404(klass, **kwargs):
try:
return klass._default_manager.get_object(**kwargs)
return klass._default_manager.get(**kwargs)
except klass.DoesNotExist:
raise Http404