mirror of
https://github.com/django/django.git
synced 2025-06-05 11:39:13 +00:00
Fixed doc references to django.db.models.query.QuerySet
and converted some tabs that were introduced in r16699 to spaces.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@16915 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
ec5bfed57a
commit
2eadc418af
@ -321,9 +321,9 @@ will get you started for now.
|
|||||||
A shortcut: get_object_or_404()
|
A shortcut: get_object_or_404()
|
||||||
-------------------------------
|
-------------------------------
|
||||||
|
|
||||||
It's a very common idiom to use :meth:`~django.db.models.QuerySet.get` and raise
|
It's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`
|
||||||
:exc:`~django.http.Http404` if the object doesn't exist. Django provides a
|
and raise :exc:`~django.http.Http404` if the object doesn't exist. Django
|
||||||
shortcut. Here's the ``detail()`` view, rewritten::
|
provides a shortcut. Here's the ``detail()`` view, rewritten::
|
||||||
|
|
||||||
from django.shortcuts import render_to_response, get_object_or_404
|
from django.shortcuts import render_to_response, get_object_or_404
|
||||||
# ...
|
# ...
|
||||||
@ -333,8 +333,8 @@ shortcut. Here's the ``detail()`` view, rewritten::
|
|||||||
|
|
||||||
The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
|
The :func:`~django.shortcuts.get_object_or_404` function takes a Django model
|
||||||
as its first argument and an arbitrary number of keyword arguments, which it
|
as its first argument and an arbitrary number of keyword arguments, which it
|
||||||
passes to the module's :meth:`~django.db.models.QuerySet.get` function. It
|
passes to the module's :meth:`~django.db.models.query.QuerySet.get` function.
|
||||||
raises :exc:`~django.http.Http404` if the object doesn't exist.
|
It raises :exc:`~django.http.Http404` if the object doesn't exist.
|
||||||
|
|
||||||
.. admonition:: Philosophy
|
.. admonition:: Philosophy
|
||||||
|
|
||||||
@ -349,9 +349,9 @@ raises :exc:`~django.http.Http404` if the object doesn't exist.
|
|||||||
|
|
||||||
There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
|
There's also a :func:`~django.shortcuts.get_list_or_404` function, which works
|
||||||
just as :func:`~django.shortcuts.get_object_or_404` -- except using
|
just as :func:`~django.shortcuts.get_object_or_404` -- except using
|
||||||
:meth:`~django.db.models.QuerySet.filter` instead of
|
:meth:`~django.db.models.query.QuerySet.filter` instead of
|
||||||
:meth:`~django.db.models.QuerySet.get`. It raises :exc:`~django.http.Http404` if
|
:meth:`~django.db.models.query.QuerySet.get`. It raises
|
||||||
the list is empty.
|
:exc:`~django.http.Http404` if the list is empty.
|
||||||
|
|
||||||
Write a 404 (page not found) view
|
Write a 404 (page not found) view
|
||||||
=================================
|
=================================
|
||||||
|
@ -388,7 +388,7 @@ MultipleObjectTemplateResponseMixin
|
|||||||
that operate upon a list of object instances. Requires that the view it is
|
that operate upon a list of object instances. Requires that the view it is
|
||||||
mixed with provides ``self.object_list``, the list of object instances that
|
mixed with provides ``self.object_list``, the list of object instances that
|
||||||
the view is operating on. ``self.object_list`` may be, but is not required
|
the view is operating on. ``self.object_list`` may be, but is not required
|
||||||
to be, a :class:`~django.db.models.Queryset`.
|
to be, a :class:`~django.db.models.query.QuerySet`.
|
||||||
|
|
||||||
**Extends**
|
**Extends**
|
||||||
|
|
||||||
@ -814,7 +814,7 @@ BaseDateListView
|
|||||||
Returns the list of dates of type ``date_type`` for which
|
Returns the list of dates of type ``date_type`` for which
|
||||||
``queryset`` contains entries. For example, ``get_date_list(qs,
|
``queryset`` contains entries. For example, ``get_date_list(qs,
|
||||||
'year')`` will return the list of years for which ``qs`` has entries.
|
'year')`` will return the list of years for which ``qs`` has entries.
|
||||||
See :meth:`~django.db.models.QuerySet.dates()` for the
|
See :meth:`~django.db.models.query.QuerySet.dates()` for the
|
||||||
ways that the ``date_type`` argument can be used.
|
ways that the ``date_type`` argument can be used.
|
||||||
|
|
||||||
|
|
||||||
|
@ -23,13 +23,14 @@ models. For example, here's the user module from Django's built-in
|
|||||||
.. warning::
|
.. warning::
|
||||||
|
|
||||||
The "delete selected objects" action uses :meth:`QuerySet.delete()
|
The "delete selected objects" action uses :meth:`QuerySet.delete()
|
||||||
<django.db.models.QuerySet.delete>` for efficiency reasons, which has an
|
<django.db.models.query.QuerySet.delete>` for efficiency reasons, which
|
||||||
important caveat: your model's ``delete()`` method will not be called.
|
has an important caveat: your model's ``delete()`` method will not be
|
||||||
|
called.
|
||||||
|
|
||||||
If you wish to override this behavior, simply write a custom action which
|
If you wish to override this behavior, simply write a custom action which
|
||||||
accomplishes deletion in your preferred manner -- for example, by calling
|
accomplishes deletion in your preferred manner -- for example, by calling
|
||||||
``Model.delete()`` for each of the selected items.
|
``Model.delete()`` for each of the selected items.
|
||||||
|
|
||||||
For more background on bulk deletion, see the documentation on :ref:`object
|
For more background on bulk deletion, see the documentation on :ref:`object
|
||||||
deletion <topics-db-queries-delete>`.
|
deletion <topics-db-queries-delete>`.
|
||||||
|
|
||||||
@ -55,10 +56,10 @@ simple news application with an ``Article`` model::
|
|||||||
title = models.CharField(max_length=100)
|
title = models.CharField(max_length=100)
|
||||||
body = models.TextField()
|
body = models.TextField()
|
||||||
status = models.CharField(max_length=1, choices=STATUS_CHOICES)
|
status = models.CharField(max_length=1, choices=STATUS_CHOICES)
|
||||||
|
|
||||||
def __unicode__(self):
|
def __unicode__(self):
|
||||||
return self.title
|
return self.title
|
||||||
|
|
||||||
A common task we might perform with a model like this is to update an
|
A common task we might perform with a model like this is to update an
|
||||||
article's status from "draft" to "published". We could easily do this in the
|
article's status from "draft" to "published". We could easily do this in the
|
||||||
admin one article at a time, but if we wanted to bulk-publish a group of
|
admin one article at a time, but if we wanted to bulk-publish a group of
|
||||||
@ -70,29 +71,29 @@ Writing action functions
|
|||||||
|
|
||||||
First, we'll need to write a function that gets called when the action is
|
First, we'll need to write a function that gets called when the action is
|
||||||
trigged from the admin. Action functions are just regular functions that take
|
trigged from the admin. Action functions are just regular functions that take
|
||||||
three arguments:
|
three arguments:
|
||||||
|
|
||||||
* The current :class:`ModelAdmin`
|
* The current :class:`ModelAdmin`
|
||||||
* An :class:`~django.http.HttpRequest` representing the current request,
|
* An :class:`~django.http.HttpRequest` representing the current request,
|
||||||
* A :class:`~django.db.models.QuerySet` containing the set of objects
|
* A :class:`~django.db.models.query.QuerySet` containing the set of
|
||||||
selected by the user.
|
objects selected by the user.
|
||||||
|
|
||||||
Our publish-these-articles function won't need the :class:`ModelAdmin` or the
|
Our publish-these-articles function won't need the :class:`ModelAdmin` or the
|
||||||
request object, but we will use the queryset::
|
request object, but we will use the queryset::
|
||||||
|
|
||||||
def make_published(modeladmin, request, queryset):
|
def make_published(modeladmin, request, queryset):
|
||||||
queryset.update(status='p')
|
queryset.update(status='p')
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
For the best performance, we're using the queryset's :ref:`update method
|
For the best performance, we're using the queryset's :ref:`update method
|
||||||
<topics-db-queries-update>`. Other types of actions might need to deal
|
<topics-db-queries-update>`. Other types of actions might need to deal
|
||||||
with each object individually; in these cases we'd just iterate over the
|
with each object individually; in these cases we'd just iterate over the
|
||||||
queryset::
|
queryset::
|
||||||
|
|
||||||
for obj in queryset:
|
for obj in queryset:
|
||||||
do_something_with(obj)
|
do_something_with(obj)
|
||||||
|
|
||||||
That's actually all there is to writing an action! However, we'll take one
|
That's actually all there is to writing an action! However, we'll take one
|
||||||
more optional-but-useful step and give the action a "nice" title in the admin.
|
more optional-but-useful step and give the action a "nice" title in the admin.
|
||||||
By default, this action would appear in the action list as "Make published" --
|
By default, this action would appear in the action list as "Make published" --
|
||||||
@ -103,13 +104,13 @@ can provide a better, more human-friendly name by giving the
|
|||||||
def make_published(modeladmin, request, queryset):
|
def make_published(modeladmin, request, queryset):
|
||||||
queryset.update(status='p')
|
queryset.update(status='p')
|
||||||
make_published.short_description = "Mark selected stories as published"
|
make_published.short_description = "Mark selected stories as published"
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
This might look familiar; the admin's ``list_display`` option uses the
|
This might look familiar; the admin's ``list_display`` option uses the
|
||||||
same technique to provide human-readable descriptions for callback
|
same technique to provide human-readable descriptions for callback
|
||||||
functions registered there, too.
|
functions registered there, too.
|
||||||
|
|
||||||
Adding actions to the :class:`ModelAdmin`
|
Adding actions to the :class:`ModelAdmin`
|
||||||
-----------------------------------------
|
-----------------------------------------
|
||||||
|
|
||||||
@ -130,11 +131,11 @@ the action and its registration would look like::
|
|||||||
actions = [make_published]
|
actions = [make_published]
|
||||||
|
|
||||||
admin.site.register(Article, ArticleAdmin)
|
admin.site.register(Article, ArticleAdmin)
|
||||||
|
|
||||||
That code will give us an admin change list that looks something like this:
|
That code will give us an admin change list that looks something like this:
|
||||||
|
|
||||||
.. image:: _images/article_actions.png
|
.. image:: _images/article_actions.png
|
||||||
|
|
||||||
That's really all there is to it! If you're itching to write your own actions,
|
That's really all there is to it! If you're itching to write your own actions,
|
||||||
you now know enough to get started. The rest of this document just covers more
|
you now know enough to get started. The rest of this document just covers more
|
||||||
advanced techniques.
|
advanced techniques.
|
||||||
@ -157,13 +158,13 @@ That's easy enough to do::
|
|||||||
|
|
||||||
class ArticleAdmin(admin.ModelAdmin):
|
class ArticleAdmin(admin.ModelAdmin):
|
||||||
...
|
...
|
||||||
|
|
||||||
actions = ['make_published']
|
actions = ['make_published']
|
||||||
|
|
||||||
def make_published(self, request, queryset):
|
def make_published(self, request, queryset):
|
||||||
queryset.update(status='p')
|
queryset.update(status='p')
|
||||||
make_published.short_description = "Mark selected stories as published"
|
make_published.short_description = "Mark selected stories as published"
|
||||||
|
|
||||||
Notice first that we've moved ``make_published`` into a method and renamed the
|
Notice first that we've moved ``make_published`` into a method and renamed the
|
||||||
`modeladmin` parameter to `self`, and second that we've now put the string
|
`modeladmin` parameter to `self`, and second that we've now put the string
|
||||||
``'make_published'`` in ``actions`` instead of a direct function reference. This
|
``'make_published'`` in ``actions`` instead of a direct function reference. This
|
||||||
@ -193,7 +194,7 @@ This make the action match what the admin itself does after successfully
|
|||||||
performing an action:
|
performing an action:
|
||||||
|
|
||||||
.. image:: _images/article_actions_message.png
|
.. image:: _images/article_actions_message.png
|
||||||
|
|
||||||
Actions that provide intermediate pages
|
Actions that provide intermediate pages
|
||||||
---------------------------------------
|
---------------------------------------
|
||||||
|
|
||||||
@ -230,7 +231,7 @@ that simply redirects to your custom export view::
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
from django.http import HttpResponseRedirect
|
from django.http import HttpResponseRedirect
|
||||||
|
|
||||||
def export_selected_objects(modeladmin, request, queryset):
|
def export_selected_objects(modeladmin, request, queryset):
|
||||||
selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
|
selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
|
||||||
ct = ContentType.objects.get_for_model(queryset.model)
|
ct = ContentType.objects.get_for_model(queryset.model)
|
||||||
@ -255,7 +256,7 @@ Making actions available site-wide
|
|||||||
example::
|
example::
|
||||||
|
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
|
||||||
admin.site.add_action(export_selected_objects)
|
admin.site.add_action(export_selected_objects)
|
||||||
|
|
||||||
This makes the `export_selected_objects` action globally available as an
|
This makes the `export_selected_objects` action globally available as an
|
||||||
@ -263,7 +264,7 @@ Making actions available site-wide
|
|||||||
a name -- good if you later want to programatically :ref:`remove the action
|
a name -- good if you later want to programatically :ref:`remove the action
|
||||||
<disabling-admin-actions>` -- by passing a second argument to
|
<disabling-admin-actions>` -- by passing a second argument to
|
||||||
:meth:`AdminSite.add_action()`::
|
:meth:`AdminSite.add_action()`::
|
||||||
|
|
||||||
admin.site.add_action(export_selected_objects, 'export_selected')
|
admin.site.add_action(export_selected_objects, 'export_selected')
|
||||||
|
|
||||||
.. _disabling-admin-actions:
|
.. _disabling-admin-actions:
|
||||||
@ -282,32 +283,32 @@ Disabling a site-wide action
|
|||||||
|
|
||||||
If you need to disable a :ref:`site-wide action <adminsite-actions>` you can
|
If you need to disable a :ref:`site-wide action <adminsite-actions>` you can
|
||||||
call :meth:`AdminSite.disable_action()`.
|
call :meth:`AdminSite.disable_action()`.
|
||||||
|
|
||||||
For example, you can use this method to remove the built-in "delete selected
|
For example, you can use this method to remove the built-in "delete selected
|
||||||
objects" action::
|
objects" action::
|
||||||
|
|
||||||
admin.site.disable_action('delete_selected')
|
admin.site.disable_action('delete_selected')
|
||||||
|
|
||||||
Once you've done the above, that action will no longer be available
|
Once you've done the above, that action will no longer be available
|
||||||
site-wide.
|
site-wide.
|
||||||
|
|
||||||
If, however, you need to re-enable a globally-disabled action for one
|
If, however, you need to re-enable a globally-disabled action for one
|
||||||
particular model, simply list it explicitly in your ``ModelAdmin.actions``
|
particular model, simply list it explicitly in your ``ModelAdmin.actions``
|
||||||
list::
|
list::
|
||||||
|
|
||||||
# Globally disable delete selected
|
# Globally disable delete selected
|
||||||
admin.site.disable_action('delete_selected')
|
admin.site.disable_action('delete_selected')
|
||||||
|
|
||||||
# This ModelAdmin will not have delete_selected available
|
# This ModelAdmin will not have delete_selected available
|
||||||
class SomeModelAdmin(admin.ModelAdmin):
|
class SomeModelAdmin(admin.ModelAdmin):
|
||||||
actions = ['some_other_action']
|
actions = ['some_other_action']
|
||||||
...
|
...
|
||||||
|
|
||||||
# This one will
|
# This one will
|
||||||
class AnotherModelAdmin(admin.ModelAdmin):
|
class AnotherModelAdmin(admin.ModelAdmin):
|
||||||
actions = ['delete_selected', 'a_third_action']
|
actions = ['delete_selected', 'a_third_action']
|
||||||
...
|
...
|
||||||
|
|
||||||
|
|
||||||
Disabling all actions for a particular :class:`ModelAdmin`
|
Disabling all actions for a particular :class:`ModelAdmin`
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
@ -317,7 +318,7 @@ set :attr:`ModelAdmin.actions` to ``None``::
|
|||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
actions = None
|
actions = None
|
||||||
|
|
||||||
This tells the :class:`ModelAdmin` to not display or allow any actions,
|
This tells the :class:`ModelAdmin` to not display or allow any actions,
|
||||||
including any :ref:`site-wide actions <adminsite-actions>`.
|
including any :ref:`site-wide actions <adminsite-actions>`.
|
||||||
|
|
||||||
@ -326,7 +327,7 @@ Conditionally enabling or disabling actions
|
|||||||
|
|
||||||
.. method:: ModelAdmin.get_actions(request)
|
.. method:: ModelAdmin.get_actions(request)
|
||||||
|
|
||||||
Finally, you can conditionally enable or disable actions on a per-request
|
Finally, you can conditionally enable or disable actions on a per-request
|
||||||
(and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`.
|
(and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`.
|
||||||
|
|
||||||
This returns a dictionary of actions allowed. The keys are action names, and
|
This returns a dictionary of actions allowed. The keys are action names, and
|
||||||
@ -336,15 +337,15 @@ Conditionally enabling or disabling actions
|
|||||||
the list gathered by the superclass. For example, if I only wanted users
|
the list gathered by the superclass. For example, if I only wanted users
|
||||||
whose names begin with 'J' to be able to delete objects in bulk, I could do
|
whose names begin with 'J' to be able to delete objects in bulk, I could do
|
||||||
the following::
|
the following::
|
||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
...
|
...
|
||||||
|
|
||||||
def get_actions(self, request):
|
def get_actions(self, request):
|
||||||
actions = super(MyModelAdmin, self).get_actions(request)
|
actions = super(MyModelAdmin, self).get_actions(request)
|
||||||
if request.user.username[0].upper() != 'J':
|
if request.user.username[0].upper() != 'J':
|
||||||
if 'delete_selected' in actions:
|
if 'delete_selected' in actions:
|
||||||
del actions['delete_selected']
|
del actions['delete_selected']
|
||||||
return actions
|
return actions
|
||||||
|
|
||||||
|
|
||||||
|
@ -713,13 +713,14 @@ subclass::
|
|||||||
.. attribute:: ModelAdmin.list_select_related
|
.. attribute:: ModelAdmin.list_select_related
|
||||||
|
|
||||||
Set ``list_select_related`` to tell Django to use
|
Set ``list_select_related`` to tell Django to use
|
||||||
:meth:`~django.db.models.QuerySet.select_related` in retrieving the list of
|
:meth:`~django.db.models.query.QuerySet.select_related` in retrieving
|
||||||
objects on the admin change list page. This can save you a bunch of
|
the list of objects on the admin change list page. This can save you a
|
||||||
database queries.
|
bunch of database queries.
|
||||||
|
|
||||||
The value should be either ``True`` or ``False``. Default is ``False``.
|
The value should be either ``True`` or ``False``. Default is ``False``.
|
||||||
|
|
||||||
Note that Django will use :meth:`~django.db.models.QuerySet.select_related`,
|
Note that Django will use
|
||||||
|
:meth:`~django.db.models.query.QuerySet.select_related`,
|
||||||
regardless of this setting if one of the ``list_display`` fields is a
|
regardless of this setting if one of the ``list_display`` fields is a
|
||||||
``ForeignKey``.
|
``ForeignKey``.
|
||||||
|
|
||||||
@ -1182,9 +1183,9 @@ templates used by the :class:`ModelAdmin` views:
|
|||||||
.. method:: ModelAdmin.queryset(self, request)
|
.. method:: ModelAdmin.queryset(self, request)
|
||||||
|
|
||||||
The ``queryset`` method on a ``ModelAdmin`` returns a
|
The ``queryset`` method on a ``ModelAdmin`` returns a
|
||||||
:class:`~django.db.models.QuerySet` of all model instances that can be
|
:class:`~django.db.models.query.QuerySet` of all model instances that
|
||||||
edited by the admin site. One use case for overriding this method is
|
can be edited by the admin site. One use case for overriding this method
|
||||||
to show objects owned by the logged-in user::
|
is to show objects owned by the logged-in user::
|
||||||
|
|
||||||
class MyModelAdmin(admin.ModelAdmin):
|
class MyModelAdmin(admin.ModelAdmin):
|
||||||
def queryset(self, request):
|
def queryset(self, request):
|
||||||
|
@ -116,7 +116,8 @@ model it represents, or to retrieve objects from that model:
|
|||||||
|
|
||||||
Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the
|
Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the
|
||||||
model the :class:`~django.contrib.contenttypes.models.ContentType`
|
model the :class:`~django.contrib.contenttypes.models.ContentType`
|
||||||
represents, and does :meth:`a get() lookup <django.db.models.QuerySet.get>`
|
represents, and does
|
||||||
|
:meth:`a get() lookup <django.db.models.query.QuerySet.get>`
|
||||||
on that model, returning the corresponding object.
|
on that model, returning the corresponding object.
|
||||||
|
|
||||||
.. method:: ContentType.model_class()
|
.. method:: ContentType.model_class()
|
||||||
@ -416,9 +417,9 @@ might be tempted to try something like::
|
|||||||
|
|
||||||
This will not work correctly, however. The generic relation adds extra filters
|
This will not work correctly, however. The generic relation adds extra filters
|
||||||
to the queryset to ensure the correct content type, but the
|
to the queryset to ensure the correct content type, but the
|
||||||
:meth:`~django.db.models.QuerySet.aggregate` method doesn't take them into
|
:meth:`~django.db.models.query.QuerySet.aggregate` method doesn't take them
|
||||||
account. For now, if you need aggregates on generic relations, you'll need
|
into account. For now, if you need aggregates on generic relations, you'll
|
||||||
to calculate them without using the aggregation API.
|
need to calculate them without using the aggregation API.
|
||||||
|
|
||||||
Generic relations in forms and admin
|
Generic relations in forms and admin
|
||||||
------------------------------------
|
------------------------------------
|
||||||
|
@ -119,7 +119,7 @@ A complete reference can be found in the :ref:`spatial lookup reference
|
|||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
GeoDjango constructs spatial SQL with the :class:`GeoQuerySet`, a
|
GeoDjango constructs spatial SQL with the :class:`GeoQuerySet`, a
|
||||||
subclass of :class:`~django.db.models.QuerySet`. The
|
subclass of :class:`~django.db.models.query.QuerySet`. The
|
||||||
:class:`GeoManager` instance attached to your model is what
|
:class:`GeoManager` instance attached to your model is what
|
||||||
enables use of :class:`GeoQuerySet`.
|
enables use of :class:`GeoQuerySet`.
|
||||||
|
|
||||||
|
@ -89,7 +89,7 @@ Django quotes column and table names behind the scenes.
|
|||||||
|
|
||||||
get_latest_by = "order_date"
|
get_latest_by = "order_date"
|
||||||
|
|
||||||
See the docs for :meth:`~django.db.models.QuerySet.latest` for more.
|
See the docs for :meth:`~django.db.models.query.QuerySet.latest` for more.
|
||||||
|
|
||||||
``managed``
|
``managed``
|
||||||
-----------
|
-----------
|
||||||
|
@ -106,11 +106,11 @@ described here.
|
|||||||
|
|
||||||
.. admonition:: You can't share pickles between versions
|
.. admonition:: You can't share pickles between versions
|
||||||
|
|
||||||
Pickles of QuerySets are only valid for the version of Django that
|
Pickles of QuerySets are only valid for the version of Django that
|
||||||
was used to generate them. If you generate a pickle using Django
|
was used to generate them. If you generate a pickle using Django
|
||||||
version N, there is no guarantee that pickle will be readable with
|
version N, there is no guarantee that pickle will be readable with
|
||||||
Django version N+1. Pickles should not be used as part of a long-term
|
Django version N+1. Pickles should not be used as part of a long-term
|
||||||
archival strategy.
|
archival strategy.
|
||||||
|
|
||||||
.. _queryset-api:
|
.. _queryset-api:
|
||||||
|
|
||||||
@ -133,9 +133,9 @@ Though you usually won't create one manually — you'll go through a
|
|||||||
|
|
||||||
.. attribute:: ordered
|
.. attribute:: ordered
|
||||||
|
|
||||||
``True`` if the ``QuerySet`` is ordered — i.e. has an
|
``True`` if the ``QuerySet`` is ordered — i.e. has an
|
||||||
:meth:`order_by()` clause or a default ordering on the model.
|
:meth:`order_by()` clause or a default ordering on the model.
|
||||||
``False`` otherwise.
|
``False`` otherwise.
|
||||||
|
|
||||||
.. attribute:: db
|
.. attribute:: db
|
||||||
|
|
||||||
@ -468,8 +468,8 @@ This restriction has been lifted, and you can now also refer to fields on
|
|||||||
related models with reverse relations through ``OneToOneField``, ``ForeignKey``
|
related models with reverse relations through ``OneToOneField``, ``ForeignKey``
|
||||||
and ``ManyToManyField`` attributes::
|
and ``ManyToManyField`` attributes::
|
||||||
|
|
||||||
Blog.objects.values('name', 'entry__headline')
|
Blog.objects.values('name', 'entry__headline')
|
||||||
[{'name': 'My blog', 'entry__headline': 'An entry'},
|
[{'name': 'My blog', 'entry__headline': 'An entry'},
|
||||||
{'name': 'My blog', 'entry__headline': 'Another entry'}, ...]
|
{'name': 'My blog', 'entry__headline': 'Another entry'}, ...]
|
||||||
|
|
||||||
.. warning::
|
.. warning::
|
||||||
@ -788,62 +788,64 @@ of the arguments is required, but you should use at least one of them.
|
|||||||
|
|
||||||
SELECT * FROM blog_entry WHERE id IN (3, 4, 5, 20);
|
SELECT * FROM blog_entry WHERE id IN (3, 4, 5, 20);
|
||||||
|
|
||||||
Be careful when using the ``tables`` parameter if you're specifying
|
Be careful when using the ``tables`` parameter if you're specifying
|
||||||
tables that are already used in the query. When you add extra tables
|
tables that are already used in the query. When you add extra tables
|
||||||
via the ``tables`` parameter, Django assumes you want that table
|
via the ``tables`` parameter, Django assumes you want that table
|
||||||
included an extra time, if it is already included. That creates a
|
included an extra time, if it is already included. That creates a
|
||||||
problem, since the table name will then be given an alias. If a table
|
problem, since the table name will then be given an alias. If a table
|
||||||
appears multiple times in an SQL statement, the second and subsequent
|
appears multiple times in an SQL statement, the second and subsequent
|
||||||
occurrences must use aliases so the database can tell them apart. If
|
occurrences must use aliases so the database can tell them apart. If
|
||||||
you're referring to the extra table you added in the extra ``where``
|
you're referring to the extra table you added in the extra ``where``
|
||||||
parameter this is going to cause errors.
|
parameter this is going to cause errors.
|
||||||
|
|
||||||
Normally you'll only be adding extra tables that don't already appear
|
Normally you'll only be adding extra tables that don't already appear
|
||||||
in the query. However, if the case outlined above does occur, there are
|
in the query. However, if the case outlined above does occur, there are
|
||||||
a few solutions. First, see if you can get by without including the
|
a few solutions. First, see if you can get by without including the
|
||||||
extra table and use the one already in the query. If that isn't
|
extra table and use the one already in the query. If that isn't
|
||||||
possible, put your ``extra()`` call at the front of the queryset
|
possible, put your ``extra()`` call at the front of the queryset
|
||||||
construction so that your table is the first use of that table.
|
construction so that your table is the first use of that table.
|
||||||
Finally, if all else fails, look at the query produced and rewrite your
|
Finally, if all else fails, look at the query produced and rewrite your
|
||||||
``where`` addition to use the alias given to your extra table. The
|
``where`` addition to use the alias given to your extra table. The
|
||||||
alias will be the same each time you construct the queryset in the same
|
alias will be the same each time you construct the queryset in the same
|
||||||
way, so you can rely upon the alias name to not change.
|
way, so you can rely upon the alias name to not change.
|
||||||
|
|
||||||
* ``order_by``
|
* ``order_by``
|
||||||
If you need to order the resulting queryset using some of the new
|
|
||||||
fields or tables you have included via ``extra()`` use the ``order_by``
|
If you need to order the resulting queryset using some of the new
|
||||||
parameter to ``extra()`` and pass in a sequence of strings. These
|
fields or tables you have included via ``extra()`` use the ``order_by``
|
||||||
strings should either be model fields (as in the normal
|
parameter to ``extra()`` and pass in a sequence of strings. These
|
||||||
:meth:`order_by()` method on querysets), of the form
|
strings should either be model fields (as in the normal
|
||||||
``table_name.column_name`` or an alias for a column that you specified
|
:meth:`order_by()` method on querysets), of the form
|
||||||
in the ``select`` parameter to ``extra()``.
|
``table_name.column_name`` or an alias for a column that you specified
|
||||||
|
in the ``select`` parameter to ``extra()``.
|
||||||
|
|
||||||
For example::
|
For example::
|
||||||
|
|
||||||
q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
|
q = Entry.objects.extra(select={'is_recent': "pub_date > '2006-01-01'"})
|
||||||
q = q.extra(order_by = ['-is_recent'])
|
q = q.extra(order_by = ['-is_recent'])
|
||||||
|
|
||||||
This would sort all the items for which ``is_recent`` is true to the
|
This would sort all the items for which ``is_recent`` is true to the
|
||||||
front of the result set (``True`` sorts before ``False`` in a
|
front of the result set (``True`` sorts before ``False`` in a
|
||||||
descending ordering).
|
descending ordering).
|
||||||
|
|
||||||
This shows, by the way, that you can make multiple calls to ``extra()``
|
This shows, by the way, that you can make multiple calls to ``extra()``
|
||||||
and it will behave as you expect (adding new constraints each time).
|
and it will behave as you expect (adding new constraints each time).
|
||||||
|
|
||||||
* ``params``
|
* ``params``
|
||||||
The ``where`` parameter described above may use standard Python
|
|
||||||
database string placeholders — ``'%s'`` to indicate parameters the
|
The ``where`` parameter described above may use standard Python
|
||||||
database engine should automatically quote. The ``params`` argument is
|
database string placeholders — ``'%s'`` to indicate parameters the
|
||||||
a list of any extra parameters to be substituted.
|
database engine should automatically quote. The ``params`` argument is
|
||||||
|
a list of any extra parameters to be substituted.
|
||||||
|
|
||||||
Example::
|
Example::
|
||||||
|
|
||||||
Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
|
Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
|
||||||
|
|
||||||
Always use ``params`` instead of embedding values directly into
|
Always use ``params`` instead of embedding values directly into
|
||||||
``where`` because ``params`` will ensure values are quoted correctly
|
``where`` because ``params`` will ensure values are quoted correctly
|
||||||
according to your particular backend. For example, quotes will be
|
according to your particular backend. For example, quotes will be
|
||||||
escaped correctly.
|
escaped correctly.
|
||||||
|
|
||||||
Bad::
|
Bad::
|
||||||
|
|
||||||
|
@ -70,8 +70,8 @@ particular fields, you can now tell Django not to retrieve them from the
|
|||||||
database.
|
database.
|
||||||
|
|
||||||
You'll do this with the new queryset methods
|
You'll do this with the new queryset methods
|
||||||
:meth:`~django.db.models.QuerySet.defer` and
|
:meth:`~django.db.models.query.QuerySet.defer` and
|
||||||
:meth:`~django.db.models.QuerySet.only`.
|
:meth:`~django.db.models.query.QuerySet.only`.
|
||||||
|
|
||||||
New admin features
|
New admin features
|
||||||
------------------
|
------------------
|
||||||
|
@ -257,8 +257,8 @@ particular fields, you can now tell Django not to retrieve them from the
|
|||||||
database.
|
database.
|
||||||
|
|
||||||
You'll do this with the new queryset methods
|
You'll do this with the new queryset methods
|
||||||
:meth:`~django.db.models.QuerySet.defer` and
|
:meth:`~django.db.models.query.QuerySet.defer` and
|
||||||
:meth:`~django.db.models.QuerySet.only`.
|
:meth:`~django.db.models.query.QuerySet.only`.
|
||||||
|
|
||||||
Testing improvements
|
Testing improvements
|
||||||
--------------------
|
--------------------
|
||||||
|
@ -349,10 +349,10 @@ without any harmful effects, since that is already playing a role in the
|
|||||||
query.
|
query.
|
||||||
|
|
||||||
This behavior is the same as that noted in the queryset documentation for
|
This behavior is the same as that noted in the queryset documentation for
|
||||||
:meth:`~django.db.models.QuerySet.distinct` and the general rule is the same:
|
:meth:`~django.db.models.query.QuerySet.distinct` and the general rule is the
|
||||||
normally you won't want extra columns playing a part in the result, so clear
|
same: normally you won't want extra columns playing a part in the result, so
|
||||||
out the ordering, or at least make sure it's restricted only to those fields
|
clear out the ordering, or at least make sure it's restricted only to those
|
||||||
you also select in a ``values()`` call.
|
fields you also select in a ``values()`` call.
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
You might reasonably ask why Django doesn't remove the extraneous columns
|
You might reasonably ask why Django doesn't remove the extraneous columns
|
||||||
|
@ -101,7 +101,7 @@ Use ``iterator()``
|
|||||||
|
|
||||||
When you have a lot of objects, the caching behavior of the ``QuerySet`` can
|
When you have a lot of objects, the caching behavior of the ``QuerySet`` can
|
||||||
cause a large amount of memory to be used. In this case,
|
cause a large amount of memory to be used. In this case,
|
||||||
:meth:`~django.db.models.QuerySet.iterator()` may help.
|
:meth:`~django.db.models.query.QuerySet.iterator()` may help.
|
||||||
|
|
||||||
Do database work in the database rather than in Python
|
Do database work in the database rather than in Python
|
||||||
======================================================
|
======================================================
|
||||||
@ -122,7 +122,7 @@ Use ``QuerySet.extra()``
|
|||||||
------------------------
|
------------------------
|
||||||
|
|
||||||
A less portable but more powerful method is
|
A less portable but more powerful method is
|
||||||
:meth:`~django.db.models.QuerySet.extra()`, which allows some SQL to be
|
:meth:`~django.db.models.query.QuerySet.extra()`, which allows some SQL to be
|
||||||
explicitly added to the query. If that still isn't powerful enough:
|
explicitly added to the query. If that still isn't powerful enough:
|
||||||
|
|
||||||
Use raw SQL
|
Use raw SQL
|
||||||
@ -159,7 +159,8 @@ Use ``QuerySet.values()`` and ``values_list()``
|
|||||||
-----------------------------------------------
|
-----------------------------------------------
|
||||||
|
|
||||||
When you just want a ``dict`` or ``list`` of values, and don't need ORM model
|
When you just want a ``dict`` or ``list`` of values, and don't need ORM model
|
||||||
objects, make appropriate usage of :meth:`~django.db.models.QuerySet.values()`.
|
objects, make appropriate usage of
|
||||||
|
:meth:`~django.db.models.query.QuerySet.values()`.
|
||||||
These can be useful for replacing model objects in template code - as long as
|
These can be useful for replacing model objects in template code - as long as
|
||||||
the dicts you supply have the same attributes as those used in the template,
|
the dicts you supply have the same attributes as those used in the template,
|
||||||
you are fine.
|
you are fine.
|
||||||
@ -167,9 +168,9 @@ you are fine.
|
|||||||
Use ``QuerySet.defer()`` and ``only()``
|
Use ``QuerySet.defer()`` and ``only()``
|
||||||
---------------------------------------
|
---------------------------------------
|
||||||
|
|
||||||
Use :meth:`~django.db.models.QuerySet.defer()` and
|
Use :meth:`~django.db.models.query.QuerySet.defer()` and
|
||||||
:meth:`~django.db.models.QuerySet.only()` if there are database columns you
|
:meth:`~django.db.models.query.QuerySet.only()` if there are database columns
|
||||||
know that you won't need (or won't need in most cases) to avoid loading
|
you know that you won't need (or won't need in most cases) to avoid loading
|
||||||
them. Note that if you *do* use them, the ORM will have to go and get them in
|
them. Note that if you *do* use them, the ORM will have to go and get them in
|
||||||
a separate query, making this a pessimization if you use it inappropriately.
|
a separate query, making this a pessimization if you use it inappropriately.
|
||||||
|
|
||||||
|
@ -346,7 +346,7 @@ This is roughly equivalent to::
|
|||||||
|
|
||||||
Note, however, that the first of these will raise ``IndexError`` while the
|
Note, however, that the first of these will raise ``IndexError`` while the
|
||||||
second will raise ``DoesNotExist`` if no objects match the given criteria. See
|
second will raise ``DoesNotExist`` if no objects match the given criteria. See
|
||||||
:meth:`~django.db.models.QuerySet.get` for more details.
|
:meth:`~django.db.models.query.QuerySet.get` for more details.
|
||||||
|
|
||||||
.. _field-lookups-intro:
|
.. _field-lookups-intro:
|
||||||
|
|
||||||
|
@ -124,8 +124,8 @@ Fields may also be left out::
|
|||||||
>>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
|
>>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
|
||||||
|
|
||||||
The ``Person`` objects returned by this query will be deferred model instances
|
The ``Person`` objects returned by this query will be deferred model instances
|
||||||
(see :meth:`~django.db.models.QuerySet.defer()`). This means that the fields
|
(see :meth:`~django.db.models.query.QuerySet.defer()`). This means that the
|
||||||
that are omitted from the query will be loaded on demand. For example::
|
fields that are omitted from the query will be loaded on demand. For example::
|
||||||
|
|
||||||
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
|
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
|
||||||
... print p.first_name, # This will be retrieved by the original query
|
... print p.first_name, # This will be retrieved by the original query
|
||||||
|
@ -21,9 +21,10 @@ At the highest level, serializing data is a very simple operation::
|
|||||||
data = serializers.serialize("xml", SomeModel.objects.all())
|
data = serializers.serialize("xml", SomeModel.objects.all())
|
||||||
|
|
||||||
The arguments to the ``serialize`` function are the format to serialize the data
|
The arguments to the ``serialize`` function are the format to serialize the data
|
||||||
to (see `Serialization formats`_) and a :class:`~django.db.models.QuerySet` to
|
to (see `Serialization formats`_) and a
|
||||||
serialize. (Actually, the second argument can be any iterator that yields Django
|
:class:`~django.db.models.query.QuerySet` to serialize. (Actually, the second
|
||||||
objects, but it'll almost always be a QuerySet).
|
argument can be any iterator that yields Django objects, but it'll almost
|
||||||
|
always be a QuerySet).
|
||||||
|
|
||||||
You can also use a serializer object directly::
|
You can also use a serializer object directly::
|
||||||
|
|
||||||
|
@ -334,7 +334,7 @@ class CategoryItem(models.Model):
|
|||||||
category = models.ForeignKey(SimpleCategory)
|
category = models.ForeignKey(SimpleCategory)
|
||||||
|
|
||||||
def __unicode__(self):
|
def __unicode__(self):
|
||||||
return "category item: " + str(self.category)
|
return "category item: " + str(self.category)
|
||||||
|
|
||||||
class OneToOneCategory(models.Model):
|
class OneToOneCategory(models.Model):
|
||||||
new_name = models.CharField(max_length=15)
|
new_name = models.CharField(max_length=15)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user