Permalink
Browse files

Fixed #15363 -- Renamed and normalized to `get_queryset` the methods …

…that return a QuerySet.
  • Loading branch information...
loic authored and charettes committed Mar 8, 2013
1 parent 477d737 commit 6983a1a540a6e6c3bd941fa15ddd8cb49f9ec74e
Showing with 588 additions and 284 deletions.
  1. +1 −1 AUTHORS
  2. +19 −12 django/contrib/admin/options.py
  3. +5 −5 django/contrib/admin/templatetags/admin_list.py
  4. +31 −8 django/contrib/admin/views/main.py
  5. +1 −1 django/contrib/auth/admin.py
  6. +2 −2 django/contrib/comments/managers.py
  7. +13 −4 django/contrib/comments/templatetags/comments.py
  8. +14 −6 django/contrib/contenttypes/generic.py
  9. +31 −31 django/contrib/gis/db/models/manager.py
  10. +2 −2 django/contrib/sites/managers.py
  11. +1 −1 django/core/serializers/__init__.py
  12. +27 −19 django/db/models/fields/related.py
  13. +46 −38 django/db/models/manager.py
  14. +7 −7 django/db/models/query.py
  15. +3 −3 django/forms/models.py
  16. +62 −0 django/utils/deprecation.py
  17. +1 −1 docs/faq/admin.txt
  18. +9 −0 docs/internals/deprecation.txt
  19. +9 −6 docs/ref/contrib/admin/index.txt
  20. +9 −9 docs/ref/models/querysets.txt
  21. +6 −0 docs/releases/1.6.txt
  22. +14 −11 docs/topics/db/managers.txt
  23. +8 −8 docs/topics/db/multi-db.txt
  24. +4 −4 tests/admin_changelist/admin.py
  25. +2 −2 tests/admin_changelist/models.py
  26. +7 −7 tests/admin_changelist/tests.py
  27. +25 −25 tests/admin_filters/tests.py
  28. +10 −10 tests/admin_ordering/tests.py
  29. +18 −18 tests/admin_views/admin.py
  30. +2 −2 tests/admin_views/customadmin.py
  31. +6 −6 tests/admin_views/tests.py
  32. +2 −2 tests/admin_widgets/models.py
  33. +5 −5 tests/custom_managers/models.py
  34. +2 −2 tests/custom_managers_regress/models.py
  35. 0 tests/deprecation/__init__.py
  36. 0 tests/deprecation/models.py
  37. +158 −0 tests/deprecation/tests.py
  38. +2 −2 tests/fixtures/models.py
  39. +2 −2 tests/generic_relations/models.py
  40. +2 −2 tests/get_object_or_404/models.py
  41. +6 −6 tests/managers_regress/models.py
  42. +2 −2 tests/modeladmin/tests.py
  43. +2 −2 tests/prefetch_related/models.py
  44. +4 −4 tests/proxy_models/models.py
  45. +4 −4 tests/queries/models.py
  46. +2 −2 tests/reverse_single_related/models.py
View
@@ -98,7 +98,7 @@ answer newbie questions, and generally made Django that much better:
Natalia Bidart <nataliabidart@gmail.com>
Mark Biggers <biggers@utsl.com>
Paul Bissex <http://e-scribe.com/>
Loic Bistuer <loic.bistuer@sixmedia.com>
Loïc Bistuer <loic.bistuer@sixmedia.com>
Simon Blanchard
Craig Blaszczyk <masterjakul@gmail.com>
David Blewett <david@dawninglight.net>
@@ -29,6 +29,7 @@
from django.utils.html import escape, escapejs
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.deprecation import RenameMethodsBase
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
@@ -64,7 +65,13 @@ class IncorrectLookupParameters(Exception):
csrf_protect_m = method_decorator(csrf_protect)
class BaseModelAdmin(six.with_metaclass(forms.MediaDefiningClass)):
class RenameBaseModelAdminMethods(forms.MediaDefiningClass, RenameMethodsBase):
renamed_methods = (
('queryset', 'get_queryset', PendingDeprecationWarning),
)
class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)):
"""Functionality common to both ModelAdmin and InlineAdmin."""
raw_id_fields = ()
@@ -239,12 +246,12 @@ def get_prepopulated_fields(self, request, obj=None):
"""
return self.prepopulated_fields
def queryset(self, request):
def get_queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_query_set()
qs = self.model._default_manager.get_queryset()
# TODO: this should be handled by some parameter to the ChangeList.
ordering = self.get_ordering(request)
if ordering:
@@ -496,7 +503,7 @@ def get_object(self, request, object_id):
returned if no match is found (or the object_id failed validation
against the primary key field).
"""
queryset = self.queryset(request)
queryset = self.get_queryset(request)
model = queryset.model
try:
object_id = model._meta.pk.to_python(object_id)
@@ -1008,7 +1015,7 @@ def add_view(self, request, form_url='', extra_context=None):
formset = FormSet(data=request.POST, files=request.FILES,
instance=new_object,
save_as_new="_saveasnew" in request.POST,
prefix=prefix, queryset=inline.queryset(request))
prefix=prefix, queryset=inline.get_queryset(request))
formsets.append(formset)
if all_valid(formsets) and form_validated:
self.save_model(request, new_object, form, False)
@@ -1034,7 +1041,7 @@ def add_view(self, request, form_url='', extra_context=None):
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=self.model(), prefix=prefix,
queryset=inline.queryset(request))
queryset=inline.get_queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
@@ -1104,7 +1111,7 @@ def change_view(self, request, object_id, form_url='', extra_context=None):
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(request.POST, request.FILES,
instance=new_object, prefix=prefix,
queryset=inline.queryset(request))
queryset=inline.get_queryset(request))
formsets.append(formset)
@@ -1124,7 +1131,7 @@ def change_view(self, request, object_id, form_url='', extra_context=None):
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset = FormSet(instance=obj, prefix=prefix,
queryset=inline.queryset(request))
queryset=inline.get_queryset(request))
formsets.append(formset)
adminForm = helpers.AdminForm(form, self.get_fieldsets(request, obj),
@@ -1209,7 +1216,7 @@ def changelist_view(self, request, extra_context=None):
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
response = self.response_action(request, queryset=cl.get_queryset(request))
if response:
return response
else:
@@ -1225,7 +1232,7 @@ def changelist_view(self, request, extra_context=None):
helpers.ACTION_CHECKBOX_NAME in request.POST and
'index' not in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_query_set(request))
response = self.response_action(request, queryset=cl.get_queryset(request))
if response:
return response
else:
@@ -1521,8 +1528,8 @@ def get_fieldsets(self, request, obj=None):
fields = list(form.base_fields) + list(self.get_readonly_fields(request, obj))
return [(None, {'fields': fields})]
def queryset(self, request):
queryset = super(InlineModelAdmin, self).queryset(request)
def get_queryset(self, request):
queryset = super(InlineModelAdmin, self).get_queryset(request)
if not self.has_change_permission(request):
queryset = queryset.none()
return queryset
@@ -306,8 +306,8 @@ def date_hierarchy(cl):
if not (year_lookup or month_lookup or day_lookup):
# select appropriate start level
date_range = cl.query_set.aggregate(first=models.Min(field_name),
last=models.Max(field_name))
date_range = cl.queryset.aggregate(first=models.Min(field_name),
last=models.Max(field_name))
if date_range['first'] and date_range['last']:
if date_range['first'].year == date_range['last'].year:
year_lookup = date_range['first'].year
@@ -325,7 +325,7 @@ def date_hierarchy(cl):
'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}]
}
elif year_lookup and month_lookup:
days = cl.query_set.filter(**{year_field: year_lookup, month_field: month_lookup})
days = cl.queryset.filter(**{year_field: year_lookup, month_field: month_lookup})
days = getattr(days, dates_or_datetimes)(field_name, 'day')
return {
'show': True,
@@ -339,7 +339,7 @@ def date_hierarchy(cl):
} for day in days]
}
elif year_lookup:
months = cl.query_set.filter(**{year_field: year_lookup})
months = cl.queryset.filter(**{year_field: year_lookup})
months = getattr(months, dates_or_datetimes)(field_name, 'month')
return {
'show': True,
@@ -353,7 +353,7 @@ def date_hierarchy(cl):
} for month in months]
}
else:
years = getattr(cl.query_set, dates_or_datetimes)(field_name, 'year')
years = getattr(cl.queryset, dates_or_datetimes)(field_name, 'year')
return {
'show': True,
'choices': [{
@@ -1,12 +1,15 @@
import operator
import warnings
from functools import reduce
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
from django.core.paginator import InvalidPage
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.fields import FieldDoesNotExist
from django.utils import six
from django.utils.datastructures import SortedDict
from django.utils.deprecation import RenameMethodsBase
from django.utils.encoding import force_str, force_text
from django.utils.translation import ugettext, ugettext_lazy
from django.utils.http import urlencode
@@ -33,14 +36,20 @@
EMPTY_CHANGELIST_VALUE = ugettext_lazy('(None)')
class ChangeList(object):
class RenameChangeListMethods(RenameMethodsBase):
renamed_methods = (
('get_query_set', 'get_queryset', PendingDeprecationWarning),
)
class ChangeList(six.with_metaclass(RenameChangeListMethods)):
def __init__(self, request, model, list_display, list_display_links,
list_filter, date_hierarchy, search_fields, list_select_related,
list_per_page, list_max_show_all, list_editable, model_admin):
self.model = model
self.opts = model._meta
self.lookup_opts = self.opts
self.root_query_set = model_admin.queryset(request)
self.root_queryset = model_admin.get_queryset(request)
self.list_display = list_display
self.list_display_links = list_display_links
self.list_filter = list_filter
@@ -70,7 +79,7 @@ def __init__(self, request, model, list_display, list_display_links,
else:
self.list_editable = list_editable
self.query = request.GET.get(SEARCH_VAR, '')
self.query_set = self.get_query_set(request)
self.queryset = self.get_queryset(request)
self.get_results(request)
if self.is_popup:
title = ugettext('Select %s')
@@ -79,6 +88,20 @@ def __init__(self, request, model, list_display, list_display_links,
self.title = title % force_text(self.opts.verbose_name)
self.pk_attname = self.lookup_opts.pk.attname
@property
def root_query_set(self):
warnings.warn("`ChangeList.root_query_set` is deprecated, "
"use `root_queryset` instead.",
PendingDeprecationWarning, 2)
return self.root_queryset
@property
def query_set(self):
warnings.warn("`ChangeList.query_set` is deprecated, "
"use `queryset` instead.",
PendingDeprecationWarning, 2)
return self.queryset
def get_filters_params(self, params=None):
"""
Returns all params except IGNORED_PARAMS
@@ -169,7 +192,7 @@ def get_query_string(self, new_params=None, remove=None):
return '?%s' % urlencode(sorted(p.items()))
def get_results(self, request):
paginator = self.model_admin.get_paginator(request, self.query_set, self.list_per_page)
paginator = self.model_admin.get_paginator(request, self.queryset, self.list_per_page)
# Get the number of objects, with admin filters applied.
result_count = paginator.count
@@ -178,15 +201,15 @@ def get_results(self, request):
# full_result_count is equal to paginator.count if no filters
# were applied
if self.get_filters_params():
full_result_count = self.root_query_set.count()
full_result_count = self.root_queryset.count()
else:
full_result_count = result_count
can_show_all = result_count <= self.list_max_show_all
multi_page = result_count > self.list_per_page
# Get the list of objects to display on this page.
if (self.show_all and can_show_all) or not multi_page:
result_list = self.query_set._clone()
result_list = self.queryset._clone()
else:
try:
result_list = paginator.page(self.page_num+1).object_list
@@ -304,13 +327,13 @@ def get_ordering_field_columns(self):
ordering_fields[idx] = 'desc' if pfx == '-' else 'asc'
return ordering_fields
def get_query_set(self, request):
def get_queryset(self, request):
# First, we collect all the declared list filters.
(self.filter_specs, self.has_filters, remaining_lookup_params,
use_distinct) = self.get_filters(request)
# Then, we let every list filter modify the queryset to its liking.
qs = self.root_query_set
qs = self.root_queryset
for filter_spec in self.filter_specs:
new_qs = filter_spec.queryset(request, qs)
if new_qs is not None:
@@ -118,7 +118,7 @@ def add_view(self, request, form_url='', extra_context=None):
def user_change_password(self, request, id, form_url=''):
if not self.has_change_permission(request):
raise PermissionDenied
user = get_object_or_404(self.queryset(request), pk=id)
user = get_object_or_404(self.get_queryset(request), pk=id)
if request.method == 'POST':
form = self.change_password_form(user, request.POST)
if form.is_valid():
@@ -8,15 +8,15 @@ def in_moderation(self):
"""
QuerySet for all comments currently in the moderation queue.
"""
return self.get_query_set().filter(is_public=False, is_removed=False)
return self.get_queryset().filter(is_public=False, is_removed=False)
def for_model(self, model):
"""
QuerySet for all comments for a particular model (either an instance or
a class).
"""
ct = ContentType.objects.get_for_model(model)
qs = self.get_query_set().filter(content_type=ct)
qs = self.get_queryset().filter(content_type=ct)
if isinstance(model, models.Model):
qs = qs.filter(object_pk=force_text(model._get_pk_val()))
return qs
@@ -3,11 +3,20 @@
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib import comments
from django.utils import six
from django.utils.deprecation import RenameMethodsBase
from django.utils.encoding import smart_text
register = template.Library()
class BaseCommentNode(template.Node):
class RenameBaseCommentNodeMethods(RenameMethodsBase):
renamed_methods = (
('get_query_set', 'get_queryset', PendingDeprecationWarning),
)
class BaseCommentNode(six.with_metaclass(RenameBaseCommentNodeMethods, template.Node)):
"""
Base helper class (abstract) for handling the get_comment_* template tags.
Looks a bit strange, but the subclasses below should make this a bit more
@@ -64,11 +73,11 @@ def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname
self.comment = comment
def render(self, context):
qs = self.get_query_set(context)
qs = self.get_queryset(context)
context[self.as_varname] = self.get_context_value_from_queryset(context, qs)
return ''
def get_query_set(self, context):
def get_queryset(self, context):
ctype, object_pk = self.get_target_ctype_pk(context)
if not object_pk:
return self.comment_model.objects.none()
@@ -205,7 +214,7 @@ def render(self, context):
"comments/%s/list.html" % ctype.app_label,
"comments/list.html"
]
qs = self.get_query_set(context)
qs = self.get_queryset(context)
context.push()
liststr = render_to_string(template_search_list, {
"comment_list" : self.get_context_value_from_queryset(context, qs)
@@ -16,10 +16,18 @@
from django.forms.models import BaseModelFormSet, modelformset_factory, save_instance
from django.contrib.admin.options import InlineModelAdmin, flatten_fieldsets
from django.contrib.contenttypes.models import ContentType
from django.utils import six
from django.utils.deprecation import RenameMethodsBase
from django.utils.encoding import smart_text
class GenericForeignKey(object):
class RenameGenericForeignKeyMethods(RenameMethodsBase):
renamed_methods = (
('get_prefetch_query_set', 'get_prefetch_queryset', PendingDeprecationWarning),
)
class GenericForeignKey(six.with_metaclass(RenameGenericForeignKeyMethods)):
"""
Provides a generic relation to any object through content-type/object-id
fields.
@@ -60,7 +68,7 @@ def get_content_type(self, obj=None, id=None, using=None):
# This should never happen. I love comments like this, don't you?
raise Exception("Impossible arguments to GFK.get_content_type!")
def get_prefetch_query_set(self, instances):
def get_prefetch_queryset(self, instances):
# For efficiency, group the instances by content type and then do one
# query per model
fk_dict = defaultdict(set)
@@ -316,21 +324,21 @@ def __init__(self, model=None, instance=None, symmetrical=None,
'%s__exact' % object_id_field_name: instance._get_pk_val(),
}
def get_query_set(self):
def get_queryset(self):
try:
return self.instance._prefetched_objects_cache[self.prefetch_cache_name]
except (AttributeError, KeyError):
db = self._db or router.db_for_read(self.model, instance=self.instance)
return super(GenericRelatedObjectManager, self).get_query_set().using(db).filter(**self.core_filters)
return super(GenericRelatedObjectManager, self).get_queryset().using(db).filter(**self.core_filters)
def get_prefetch_query_set(self, instances):
def get_prefetch_queryset(self, instances):
db = self._db or router.db_for_read(self.model, instance=instances[0])
query = {
'%s__pk' % self.content_type_field_name: self.content_type.id,
'%s__in' % self.object_id_field_name:
set(obj._get_pk_val() for obj in instances)
}
qs = super(GenericRelatedObjectManager, self).get_query_set().using(db).filter(**query)
qs = super(GenericRelatedObjectManager, self).get_queryset().using(db).filter(**query)
# We (possibly) need to convert object IDs to the type of the
# instances' PK in order to match up instances:
object_id_converter = instances[0]._meta.pk.to_python
Oops, something went wrong.

0 comments on commit 6983a1a

Please sign in to comment.