From e0837f2cb12de5e95e621d19b186b0da43bcdee2 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Mon, 5 Oct 2015 19:07:34 -0400 Subject: [PATCH] Fixed #25508 -- Modified QuerySet.__repr__() to disambiguate it from a list. --- django/db/models/query.py | 2 +- docs/intro/overview.txt | 10 +-- docs/intro/tutorial02.txt | 17 ++-- docs/intro/tutorial05.txt | 2 +- docs/ref/contrib/contenttypes.txt | 6 +- docs/ref/contrib/gis/tutorial.txt | 10 +-- docs/ref/contrib/postgres/fields.txt | 78 ++++++++--------- docs/ref/contrib/postgres/functions.txt | 2 +- docs/ref/models/database-functions.txt | 2 +- docs/ref/models/querysets.txt | 34 ++++---- docs/releases/1.10.txt | 3 +- docs/topics/db/aggregation.txt | 2 +- docs/topics/db/examples/many_to_many.txt | 102 +++++++++++------------ docs/topics/db/examples/many_to_one.txt | 54 ++++++------ docs/topics/db/examples/one_to_one.txt | 12 +-- docs/topics/db/models.txt | 12 +-- docs/topics/forms/modelforms.txt | 2 +- tests/fixtures_regress/tests.py | 11 +-- tests/null_queries/tests.py | 2 +- tests/string_lookup/tests.py | 6 +- 20 files changed, 185 insertions(+), 184 deletions(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index b7d55b6a4b..625e1e8891 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -234,7 +234,7 @@ class QuerySet(object): data = list(self[:REPR_OUTPUT_SIZE + 1]) if len(data) > REPR_OUTPUT_SIZE: data[-1] = "...(remaining elements truncated)..." - return repr(data) + return '' % data def __len__(self): self._fetch_all() diff --git a/docs/intro/overview.txt b/docs/intro/overview.txt index 77316c2662..551310e900 100644 --- a/docs/intro/overview.txt +++ b/docs/intro/overview.txt @@ -73,7 +73,7 @@ necessary: # No reporters are in the system yet. >>> Reporter.objects.all() - [] + # Create a new Reporter. >>> r = Reporter(full_name='John Smith') @@ -87,7 +87,7 @@ necessary: # Now the new reporter is in the database. >>> Reporter.objects.all() - [] + ]> # Fields are represented as attributes on the Python object. >>> r.full_name @@ -113,7 +113,7 @@ necessary: # Now the article is in the database. >>> Article.objects.all() - [] + ]> # Article objects get API access to related Reporter objects. >>> r = a.reporter @@ -122,13 +122,13 @@ necessary: # And vice versa: Reporter objects get API access to Article objects. >>> r.article_set.all() - [] + ]> # The API follows relationships as far as you need, performing efficient # JOINs for you behind the scenes. # This finds all articles by a reporter whose name starts with "John". >>> Article.objects.filter(reporter__full_name__startswith='John') - [] + ]> # Change an object by altering its attributes and calling save(). >>> r.full_name = 'Billy Goat' diff --git a/docs/intro/tutorial02.txt b/docs/intro/tutorial02.txt index fbf15e8d1b..1e3c1accf7 100644 --- a/docs/intro/tutorial02.txt +++ b/docs/intro/tutorial02.txt @@ -401,7 +401,7 @@ Once you're in the shell, explore the :doc:`database API `:: # No questions are in the system yet. >>> Question.objects.all() - [] + # Create a new Question. # Support for time zones is enabled in the default settings file, so @@ -432,8 +432,7 @@ Once you're in the shell, explore the :doc:`database API `:: # objects.all() displays all the questions in the database. >>> Question.objects.all() - [] - + ]> Wait a minute. ```` is, utterly, an unhelpful representation of this object. Let's fix that by editing the ``Question`` model (in the @@ -494,14 +493,14 @@ Save these changes and start a new Python interactive shell by running # Make sure our __str__() addition worked. >>> Question.objects.all() - [] + ]> # Django provides a rich database lookup API that's entirely driven by # keyword arguments. >>> Question.objects.filter(id=1) - [] + ]> >>> Question.objects.filter(question_text__startswith='What') - [] + ]> # Get the question that was published this year. >>> from django.utils import timezone @@ -535,7 +534,7 @@ Save these changes and start a new Python interactive shell by running # Display any choices from the related object set -- none so far. >>> q.choice_set.all() - [] + # Create three choices. >>> q.choice_set.create(choice_text='Not much', votes=0) @@ -550,7 +549,7 @@ Save these changes and start a new Python interactive shell by running # And vice versa: Question objects get access to Choice objects. >>> q.choice_set.all() - [, , ] + , , ]> >>> q.choice_set.count() 3 @@ -560,7 +559,7 @@ Save these changes and start a new Python interactive shell by running # Find all Choices for any question whose pub_date is in this year # (reusing the 'current_year' variable we created above). >>> Choice.objects.filter(question__pub_date__year=current_year) - [, , ] + , , ]> # Let's delete one of the choices. Use delete() for that. >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') diff --git a/docs/intro/tutorial05.txt b/docs/intro/tutorial05.txt index fe108d3db9..a1b594dbc2 100644 --- a/docs/intro/tutorial05.txt +++ b/docs/intro/tutorial05.txt @@ -383,7 +383,7 @@ With that ready, we can ask the client to do some work for us:: >>> # If the following doesn't work, you probably omitted the call to >>> # setup_test_environment() described above >>> response.context['latest_question_list'] - [] + ]> Improving our view ------------------ diff --git a/docs/ref/contrib/contenttypes.txt b/docs/ref/contrib/contenttypes.txt index 7e033a8913..4a8fa22f4b 100644 --- a/docs/ref/contrib/contenttypes.txt +++ b/docs/ref/contrib/contenttypes.txt @@ -382,7 +382,7 @@ be used to retrieve their associated ``TaggedItems``:: >>> t2 = TaggedItem(content_object=b, tag='python') >>> t2.save() >>> b.tags.all() - [, ] + , ]> Defining :class:`~django.contrib.contenttypes.fields.GenericRelation` with ``related_query_name`` set allows querying from the related object:: @@ -394,7 +394,7 @@ from ``TaggedItem``:: >>> # Get all tags belonging to books containing `django` in the url >>> TaggedItem.objects.filter(bookmarks__url__contains='django') - [, ] + , ]> Just as :class:`~django.contrib.contenttypes.fields.GenericForeignKey` accepts the names of the content-type and object-ID fields as @@ -418,7 +418,7 @@ same types of lookups manually:: >>> bookmark_type = ContentType.objects.get_for_model(b) >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, ... object_id=b.id) - [, ] + , ]> Note that if the model in a :class:`~django.contrib.contenttypes.fields.GenericRelation` uses a diff --git a/docs/ref/contrib/gis/tutorial.txt b/docs/ref/contrib/gis/tutorial.txt index bf2bc28d9b..793e17a34e 100644 --- a/docs/ref/contrib/gis/tutorial.txt +++ b/docs/ref/contrib/gis/tutorial.txt @@ -588,9 +588,8 @@ Consortium (OGC). [#]_ Import the ``WorldBorder`` model, and perform a ``contains`` lookup using the ``pnt_wkt`` as the parameter:: >>> from world.models import WorldBorder - >>> qs = WorldBorder.objects.filter(mpoly__contains=pnt_wkt) - >>> qs - [] + >>> WorldBorder.objects.filter(mpoly__contains=pnt_wkt) + ]> Here, you retrieved a ``QuerySet`` with only one model: the border of the United States (exactly what you would expect). @@ -602,8 +601,7 @@ of a queryset:: >>> from django.contrib.gis.geos import Point >>> pnt = Point(12.4604, 43.9420) - >>> sm = WorldBorder.objects.get(mpoly__intersects=pnt) - >>> sm + >>> WorldBorder.objects.get(mpoly__intersects=pnt) The ``contains`` and ``intersects`` lookups are just a subset of the @@ -638,7 +636,7 @@ of abstraction:: "world_worldborder"."mpoly" FROM "world_worldborder" WHERE ST_Intersects("world_worldborder"."mpoly", ST_Transform(%s, 4326)) >>> qs # printing evaluates the queryset - [] + ]> __ http://spatialreference.org/ref/epsg/32140/ diff --git a/docs/ref/contrib/postgres/fields.txt b/docs/ref/contrib/postgres/fields.txt index 587c44a435..defd670e12 100644 --- a/docs/ref/contrib/postgres/fields.txt +++ b/docs/ref/contrib/postgres/fields.txt @@ -120,13 +120,13 @@ data. It uses the SQL operator ``@>``. For example:: >>> Post.objects.create(name='Third post', tags=['tutorial', 'django']) >>> Post.objects.filter(tags__contains=['thoughts']) - [, ] + , ]> >>> Post.objects.filter(tags__contains=['django']) - [, ] + , ]> >>> Post.objects.filter(tags__contains=['django', 'thoughts']) - [] + ]> .. fieldlookup:: arrayfield.contained_by @@ -142,10 +142,10 @@ passed. It uses the SQL operator ``<@``. For example:: >>> Post.objects.create(name='Third post', tags=['tutorial', 'django']) >>> Post.objects.filter(tags__contained_by=['thoughts', 'django']) - [, ] + , ]> >>> Post.objects.filter(tags__contained_by=['thoughts', 'django', 'tutorial']) - [, , ] + , , ]> .. fieldlookup:: arrayfield.overlap @@ -160,10 +160,10 @@ the SQL operator ``&&``. For example:: >>> Post.objects.create(name='Third post', tags=['tutorial', 'django']) >>> Post.objects.filter(tags__overlap=['thoughts']) - [, ] + , ]> >>> Post.objects.filter(tags__overlap=['thoughts', 'tutorial']) - [, , ] + , , ]> .. fieldlookup:: arrayfield.len @@ -177,7 +177,7 @@ available for :class:`~django.db.models.IntegerField`. For example:: >>> Post.objects.create(name='Second post', tags=['thoughts']) >>> Post.objects.filter(tags__len=1) - [] + ]> .. fieldlookup:: arrayfield.index @@ -194,13 +194,13 @@ example:: >>> Post.objects.create(name='Second post', tags=['thoughts']) >>> Post.objects.filter(tags__0='thoughts') - [, ] + , ]> >>> Post.objects.filter(tags__1__iexact='Django') - [] + ]> >>> Post.objects.filter(tags__276='javascript') - [] + .. note:: @@ -222,10 +222,10 @@ lookups available after the transform do not change. For example:: >>> Post.objects.create(name='Third post', tags=['django', 'python', 'thoughts']) >>> Post.objects.filter(tags__0_1=['thoughts']) - [] + ]> >>> Post.objects.filter(tags__0_2__contains='thoughts') - [, ] + , ]> .. note:: @@ -320,12 +320,12 @@ To query based on a given key, you simply use that key as the lookup name:: >>> Dog.objects.create(name='Meg', data={'breed': 'collie'}) >>> Dog.objects.filter(data__breed='collie') - [] + ]> You can chain other lookups after key lookups:: >>> Dog.objects.filter(data__breed__contains='l') - [, ] + , ]> If the key you wish to query by clashes with the name of another lookup, you need to use the :lookup:`hstorefield.contains` lookup instead. @@ -352,10 +352,10 @@ field. It uses the SQL operator ``@>``. For example:: >>> Dog.objects.create(name='Fred', data={}) >>> Dog.objects.filter(data__contains={'owner': 'Bob'}) - [, ] + , ]> >>> Dog.objects.filter(data__contains={'breed': 'collie'}) - [] + ]> .. fieldlookup:: hstorefield.contained_by @@ -372,10 +372,10 @@ example:: >>> Dog.objects.create(name='Fred', data={}) >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'}) - [, ] + , ]> >>> Dog.objects.filter(data__contained_by={'breed': 'collie'}) - [] + ]> .. fieldlookup:: hstorefield.has_key @@ -389,7 +389,7 @@ Returns objects where the given key is in the data. Uses the SQL operator >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) >>> Dog.objects.filter(data__has_key='owner') - [] + ]> .. fieldlookup:: hstorefield.has_any_keys @@ -406,7 +406,7 @@ operator ``?|``. For example:: >>> Dog.objects.create(name='Fred', data={}) >>> Dog.objects.filter(data__has_any_keys=['owner', 'breed']) - [, ] + , ]> .. fieldlookup:: hstorefield.has_keys @@ -420,7 +420,7 @@ Returns objects where all of the given keys are in the data. Uses the SQL operat >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) >>> Dog.objects.filter(data__has_keys=['breed', 'owner']) - [] + ]> .. fieldlookup:: hstorefield.keys @@ -437,7 +437,7 @@ in conjunction with lookups on >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) >>> Dog.objects.filter(data__keys__overlap=['breed', 'toy']) - [, ] + , ]> .. fieldlookup:: hstorefield.values @@ -454,7 +454,7 @@ using in conjunction with lookups on >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) >>> Dog.objects.filter(data__values__contains=['collie']) - [] + ]> JSONField --------- @@ -521,18 +521,18 @@ name:: >>> Dog.objects.create(name='Meg', data={'breed': 'collie'}) >>> Dog.objects.filter(data__breed='collie') - [] + ]> Multiple keys can be chained together to form a path lookup:: >>> Dog.objects.filter(data__owner__name='Bob') - [] + ]> If the key is an integer, it will be interpreted as an index lookup in an array:: >>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy') - [] + ]> If the key you wish to query by clashes with the name of another lookup, use the :lookup:`jsonfield.contains` lookup instead. @@ -673,7 +673,7 @@ contains '''''''' >>> Event.objects.filter(ages__contains=NumericRange(4, 5)) - [] + ]> .. fieldlookup:: rangefield.contained_by @@ -681,7 +681,7 @@ contained_by '''''''''''' >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15)) - [] + ]> .. versionadded 1.9 @@ -697,7 +697,7 @@ contained_by ... timezone.now() - datetime.timedelta(hours=1), ... timezone.now() + datetime.timedelta(hours=1), ... ) - [] + ]> .. fieldlookup:: rangefield.overlap @@ -705,7 +705,7 @@ overlap ''''''' >>> Event.objects.filter(ages__overlap=NumericRange(8, 12)) - [] + ]> Comparison functions ~~~~~~~~~~~~~~~~~~~~ @@ -726,7 +726,7 @@ all the points in the returned range are less than all those in the passed range. >>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15)) - [] + ]> .. fieldlookup:: rangefield.fully_gt @@ -738,7 +738,7 @@ the all the points in the returned range are greater than all those in the passed range. >>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15)) - [] + ]> .. fieldlookup:: rangefield.not_lt @@ -750,7 +750,7 @@ is the lower bound of the returned range is at least the lower bound of the passed range. >>> Event.objects.filter(ages__not_lt=NumericRange(0, 15)) - [, ] + , ]> .. fieldlookup:: rangefield.not_gt @@ -762,7 +762,7 @@ is the upper bound of the returned range is at most the upper bound of the passed range. >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10)) - [] + ]> .. fieldlookup:: rangefield.adjacent_to @@ -772,7 +772,7 @@ adjacent_to The returned ranges share a bound with the passed range. >>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21)) - [, ] + , ]> Querying using the bounds ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -789,7 +789,7 @@ Returned objects have the given lower bound. Can be chained to valid lookups for the base field. >>> Event.objects.filter(ages__startswith=21) - [] + ]> .. fieldlookup:: rangefield.endswith @@ -800,7 +800,7 @@ Returned objects have the given upper bound. Can be chained to valid lookups for the base field. >>> Event.objects.filter(ages__endswith=10) - [] + ]> .. fieldlookup:: rangefield.isempty @@ -811,7 +811,7 @@ Returned objects are empty ranges. Can be chained to valid lookups for a :class:`~django.db.models.BooleanField`. >>> Event.objects.filter(ages__isempty=True) - [] + Defining your own range types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/ref/contrib/postgres/functions.txt b/docs/ref/contrib/postgres/functions.txt index c97af99bfb..f4abdc2c17 100644 --- a/docs/ref/contrib/postgres/functions.txt +++ b/docs/ref/contrib/postgres/functions.txt @@ -28,4 +28,4 @@ Usage example:: >>> from django.contrib.postgres.functions import TransactionNow >>> Article.objects.filter(published__lte=TransactionNow()) - [] + ]> diff --git a/docs/ref/models/database-functions.txt b/docs/ref/models/database-functions.txt index 9c9f2641b9..fc3f25dd29 100644 --- a/docs/ref/models/database-functions.txt +++ b/docs/ref/models/database-functions.txt @@ -226,7 +226,7 @@ Usage example:: >>> from django.db.models.functions import Now >>> Article.objects.filter(published__lte=Now()) - [] + ]> .. admonition:: PostgreSQL considerations diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index ebb9019784..0887e94729 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -513,11 +513,11 @@ objects:: # This list contains a Blog object. >>> Blog.objects.filter(name__startswith='Beatles') - [] + ]> # This list contains a dictionary. >>> Blog.objects.filter(name__startswith='Beatles').values() - [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}] + The ``values()`` method takes optional positional arguments, ``*fields``, which specify field names to which the ``SELECT`` should be limited. If you specify @@ -528,9 +528,9 @@ contain a key and value for every field in the database table. Example:: >>> Blog.objects.values() - [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}], + >>> Blog.objects.values('id', 'name') - [{'id': 1, 'name': 'Beatles Blog'}] + A few subtleties that are worth mentioning: @@ -546,13 +546,13 @@ A few subtleties that are worth mentioning: For example:: >>> Entry.objects.values() - [{'blog_id': 1, 'headline': 'First Entry', ...}, ...] + >>> Entry.objects.values('blog') - [{'blog': 1}, ...] + >>> Entry.objects.values('blog_id') - [{'blog_id': 1}, ...] + * When using ``values()`` together with :meth:`distinct()`, be aware that ordering can affect the results. See the note in :meth:`distinct` for @@ -585,9 +585,9 @@ individualism. You can also refer to fields on related models with reverse relations through ``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes:: - Blog.objects.values('name', 'entry__headline') - [{'name': 'My blog', 'entry__headline': 'An entry'}, - {'name': 'My blog', 'entry__headline': 'Another entry'}, ...] + >>> Blog.objects.values('name', 'entry__headline') + .. warning:: @@ -717,7 +717,7 @@ is an instance of ``EmptyQuerySet``. Examples:: >>> Entry.objects.none() - [] + >>> from django.db.models.query import EmptyQuerySet >>> isinstance(Entry.objects.none(), EmptyQuerySet) True @@ -3015,11 +3015,11 @@ as the string based lookups passed to :meth:`~django.db.models.query.QuerySet.prefetch_related()`. For example: >>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all() - [, , ] + , , ]> # This will only execute two queries regardless of the number of Question # and Choice objects. >>> Question.objects.prefetch_related(Prefetch('choice_set')).all() - [] + ]> The ``queryset`` argument supplies a base ``QuerySet`` for the given lookup. This is useful to further filter down the prefetch operation, or to call @@ -3028,19 +3028,19 @@ relation, hence reducing the number of queries even further: >>> voted_choices = Choice.objects.filter(votes__gt=0) >>> voted_choices - [] + ]> >>> prefetch = Prefetch('choice_set', queryset=voted_choices) >>> Question.objects.prefetch_related(prefetch).get().choice_set.all() - [] + ]> The ``to_attr`` argument sets the result of the prefetch operation to a custom attribute: >>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices') >>> Question.objects.prefetch_related(prefetch).get().voted_choices - [] + ]> >>> Question.objects.prefetch_related(prefetch).get().choice_set.all() - [, , ] + , , ]> .. note:: diff --git a/docs/releases/1.10.txt b/docs/releases/1.10.txt index 2c41db2b72..bb911bb8a0 100644 --- a/docs/releases/1.10.txt +++ b/docs/releases/1.10.txt @@ -219,7 +219,8 @@ Database backend API Miscellaneous ~~~~~~~~~~~~~ -* ... +* The ``repr()`` of a ``QuerySet`` is wrapped in ````` to + disambiguate it from a plain list when debugging. .. _deprecated-features-1.10: diff --git a/docs/topics/db/aggregation.txt b/docs/topics/db/aggregation.txt index 65a1eb7ee6..22c4e483df 100644 --- a/docs/topics/db/aggregation.txt +++ b/docs/topics/db/aggregation.txt @@ -79,7 +79,7 @@ In a hurry? Here's how to do common aggregate queries, assuming the models above >>> from django.db.models import Count >>> pubs = Publisher.objects.annotate(num_books=Count('book')) >>> pubs - [, , ...] + , , ...]> >>> pubs[0].num_books 73 diff --git a/docs/topics/db/examples/many_to_many.txt b/docs/topics/db/examples/many_to_many.txt index 79605ac158..cbf8da99e2 100644 --- a/docs/topics/db/examples/many_to_many.txt +++ b/docs/topics/db/examples/many_to_many.txt @@ -93,36 +93,36 @@ Create and add a ``Publication`` to an ``Article`` in one step using ``Article`` objects have access to their related ``Publication`` objects:: >>> a1.publications.all() - [] + ]> >>> a2.publications.all() - [, , , ] + , , , ]> ``Publication`` objects have access to their related ``Article`` objects:: >>> p2.article_set.all() - [] + ]> >>> p1.article_set.all() - [, ] + , ]> >>> Publication.objects.get(id=4).article_set.all() - [] + ]> Many-to-many relationships can be queried using :ref:`lookups across relationships `:: >>> Article.objects.filter(publications__id=1) - [, ] + , ]> >>> Article.objects.filter(publications__pk=1) - [, ] + , ]> >>> Article.objects.filter(publications=1) - [, ] + , ]> >>> Article.objects.filter(publications=p1) - [, ] + , ]> >>> Article.objects.filter(publications__title__startswith="Science") - [, ] + , ]> >>> Article.objects.filter(publications__title__startswith="Science").distinct() - [] + ]> The :meth:`~django.db.models.query.QuerySet.count` function respects :meth:`~django.db.models.query.QuerySet.distinct` as well:: @@ -134,57 +134,57 @@ The :meth:`~django.db.models.query.QuerySet.count` function respects 1 >>> Article.objects.filter(publications__in=[1,2]).distinct() - [, ] + , ]> >>> Article.objects.filter(publications__in=[p1,p2]).distinct() - [, ] + , ]> Reverse m2m queries are supported (i.e., starting at the table that doesn't have a :class:`~django.db.models.ManyToManyField`):: >>> Publication.objects.filter(id=1) - [] + ]> >>> Publication.objects.filter(pk=1) - [] + ]> >>> Publication.objects.filter(article__headline__startswith="NASA") - [, , , ] + , , , ]> >>> Publication.objects.filter(article__id=1) - [] + ]> >>> Publication.objects.filter(article__pk=1) - [] + ]> >>> Publication.objects.filter(article=1) - [] + ]> >>> Publication.objects.filter(article=a1) - [] + ]> >>> Publication.objects.filter(article__in=[1,2]).distinct() - [, , , ] + , , , ]> >>> Publication.objects.filter(article__in=[a1,a2]).distinct() - [, , , ] + , , , ]> Excluding a related item works as you would expect, too (although the SQL involved is a little complex):: >>> Article.objects.exclude(publications=p2) - [] + ]> If we delete a ``Publication``, its ``Articles`` won't be able to access it:: >>> p1.delete() >>> Publication.objects.all() - [, , ] + , , ]> >>> a1 = Article.objects.get(pk=1) >>> a1.publications.all() - [] + If we delete an ``Article``, its ``Publications`` won't be able to access it:: >>> a2.delete() >>> Article.objects.all() - [] + ]> >>> p2.article_set.all() - [] + Adding via the 'other' end of an m2m:: @@ -192,61 +192,61 @@ Adding via the 'other' end of an m2m:: >>> a4.save() >>> p2.article_set.add(a4) >>> p2.article_set.all() - [] + ]> >>> a4.publications.all() - [] + ]> Adding via the other end using keywords:: >>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders') >>> p2.article_set.all() - [, ] + , ]> >>> a5 = p2.article_set.all()[1] >>> a5.publications.all() - [] + ]> Removing ``Publication`` from an ``Article``:: >>> a4.publications.remove(p2) >>> p2.article_set.all() - [] + ]> >>> a4.publications.all() - [] + And from the other end:: >>> p2.article_set.remove(a5) >>> p2.article_set.all() - [] + >>> a5.publications.all() - [] + Relation sets can be assigned. Assignment clears any existing set members:: >>> a4.publications.all() - [] + ]> >>> a4.publications = [p3] >>> a4.publications.all() - [] + ]> Relation sets can be cleared:: >>> p2.article_set.clear() >>> p2.article_set.all() - [] + And you can clear from the other end:: >>> p2.article_set.add(a4, a5) >>> p2.article_set.all() - [, ] + , ]> >>> a4.publications.all() - [, ] + , ]> >>> a4.publications.clear() >>> a4.publications.all() - [] + >>> p2.article_set.all() - [] + ]> Recreate the ``Article`` and ``Publication`` we have deleted:: @@ -261,17 +261,17 @@ go:: >>> Publication.objects.filter(title__startswith='Science').delete() >>> Publication.objects.all() - [, ] + , ]> >>> Article.objects.all() - [, , , ] + , , , ]> >>> a2.publications.all() - [] + ]> Bulk delete some articles - references to deleted objects should go:: >>> q = Article.objects.filter(headline__startswith='Django') >>> print(q) - [] + ]> >>> q.delete() After the :meth:`~django.db.models.query.QuerySet.delete`, the @@ -279,9 +279,9 @@ After the :meth:`~django.db.models.query.QuerySet.delete`, the referenced objects should be gone:: >>> print(q) - [] + >>> p1.article_set.all() - [] + ]> An alternate to calling :meth:`~django.db.models.fields.related.RelatedManager.clear` is to assign the @@ -289,11 +289,11 @@ empty set:: >>> p1.article_set = [] >>> p1.article_set.all() - [] + >>> a2.publications = [p1, new_publication] >>> a2.publications.all() - [, ] + , ]> >>> a2.publications = [] >>> a2.publications.all() - [] + diff --git a/docs/topics/db/examples/many_to_one.txt b/docs/topics/db/examples/many_to_one.txt index 93cc3f093f..64f6ab1f1b 100644 --- a/docs/topics/db/examples/many_to_one.txt +++ b/docs/topics/db/examples/many_to_one.txt @@ -90,7 +90,7 @@ Create a new article, and add it to the article set:: >>> new_article2.reporter.id 1 >>> r.article_set.all() - [, , ] + , , ]> Add the same article to a different article set - check that it moves:: @@ -108,9 +108,9 @@ Adding an object of the wrong type raises TypeError:: TypeError: 'Article' instance expected >>> r.article_set.all() - [, ] + , ]> >>> r2.article_set.all() - [] + ]> >>> r.article_set.count() 2 @@ -126,56 +126,56 @@ Use double underscores to separate relationships. This works as many levels deep as you want. There's no limit. For example:: >>> r.article_set.filter(headline__startswith='This') - [] + ]> # Find all Articles for any Reporter whose first name is "John". >>> Article.objects.filter(reporter__first_name='John') - [, ] + , ]> Exact match is implied here:: >>> Article.objects.filter(reporter__first_name='John') - [, ] + , ]> Query twice over the related field. This translates to an AND condition in the WHERE clause:: >>> Article.objects.filter(reporter__first_name='John', reporter__last_name='Smith') - [, ] + , ]> For the related lookup you can supply a primary key value or pass the related object explicitly:: >>> Article.objects.filter(reporter__pk=1) - [, ] + , ]> >>> Article.objects.filter(reporter=1) - [, ] + , ]> >>> Article.objects.filter(reporter=r) - [, ] + , ]> >>> Article.objects.filter(reporter__in=[1,2]).distinct() - [, , ] + , , ]> >>> Article.objects.filter(reporter__in=[r,r2]).distinct() - [, , ] + , , ]> You can also use a queryset instead of a literal list of instances:: >>> Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')).distinct() - [, ] + , ]> Querying in the opposite direction:: >>> Reporter.objects.filter(article__pk=1) - [] + ]> >>> Reporter.objects.filter(article=1) - [] + ]> >>> Reporter.objects.filter(article=a) - [] + ]> >>> Reporter.objects.filter(article__headline__startswith='This') - [, , ] + , , ]> >>> Reporter.objects.filter(article__headline__startswith='This').distinct() - [] + ]> Counting in the opposite direction works in conjunction with distinct():: @@ -187,30 +187,30 @@ Counting in the opposite direction works in conjunction with distinct():: Queries can go round in circles:: >>> Reporter.objects.filter(article__reporter__first_name__startswith='John') - [, , , ] + , , , ]> >>> Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct() - [] + ]> >>> Reporter.objects.filter(article__reporter=r).distinct() - [] + ]> If you delete a reporter, his articles will be deleted (assuming that the ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to ``CASCADE``, which is the default):: >>> Article.objects.all() - [, , ] + , , ]> >>> Reporter.objects.order_by('first_name') - [, ] + , ]> >>> r2.delete() >>> Article.objects.all() - [, ] + , ]> >>> Reporter.objects.order_by('first_name') - [] + ]> You can delete using a JOIN in the query:: >>> Reporter.objects.filter(article__headline__startswith='This').delete() >>> Reporter.objects.all() - [] + >>> Article.objects.all() - [] + diff --git a/docs/topics/db/examples/one_to_one.txt b/docs/topics/db/examples/one_to_one.txt index dbf46fc079..7e373a98e1 100644 --- a/docs/topics/db/examples/one_to_one.txt +++ b/docs/topics/db/examples/one_to_one.txt @@ -106,13 +106,13 @@ that there are two restaurants - Ace Hardware the Restaurant was created in the call to r.place = p2:: >>> Restaurant.objects.all() - [, ] + , ]> Place.objects.all() returns all Places, regardless of whether they have Restaurants:: >>> Place.objects.order_by('name') - [, ] + , ]> You can query the models using :ref:`lookups across relationships `:: @@ -121,9 +121,9 @@ You can query the models using :ref:`lookups across relationships >> Restaurant.objects.get(place__pk=1) >>> Restaurant.objects.filter(place__name__startswith="Demon") - [] + ]> >>> Restaurant.objects.exclude(place__address__contains="Ashland") - [] + ]> This of course works in reverse:: @@ -146,6 +146,6 @@ Add a Waiter to the Restaurant:: Query the waiters:: >>> Waiter.objects.filter(restaurant__place=p1) - [] + ]> >>> Waiter.objects.filter(restaurant__place__name__startswith="Demon") - [] + ]> diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt index 99945d4287..586ec66927 100644 --- a/docs/topics/db/models.txt +++ b/docs/topics/db/models.txt @@ -501,14 +501,14 @@ the intermediate model:: ... invite_reason="Needed a new drummer.") >>> m1.save() >>> beatles.members.all() - [] + ]> >>> ringo.group_set.all() - [] + ]> >>> m2 = Membership.objects.create(person=paul, group=beatles, ... date_joined=date(1960, 8, 1), ... invite_reason="Wanted to form a band.") >>> beatles.members.all() - [, ] + , ]> Unlike normal many-to-many fields, you *can't* use ``add``, ``create``, or assignment (i.e., ``beatles.members = [...]``) to create relationships:: @@ -537,7 +537,7 @@ used to remove all many-to-many relationships for an instance:: >>> beatles.members.clear() >>> # Note that this deletes the intermediate model instances >>> Membership.objects.all() - [] + Once you have established the many-to-many relationships by creating instances of your intermediate model, you can issue queries. Just as with normal @@ -546,7 +546,7 @@ many-to-many-related model:: # Find all the groups with a member whose name starts with 'Paul' >>> Group.objects.filter(members__name__startswith='Paul') - [] + ]> As you are using an intermediate model, you can also query on its attributes:: @@ -554,7 +554,7 @@ As you are using an intermediate model, you can also query on its attributes:: >>> Person.objects.filter( ... group__name='The Beatles', ... membership__date_joined__gt=date(1961,1,1)) - [ If you need to access a membership's information you may do so by directly querying the ``Membership`` model:: diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index 6370636d4e..189336119e 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -912,7 +912,7 @@ extra forms displayed. ``max_num`` does not prevent existing objects from being displayed:: >>> Author.objects.order_by('name') - [, , ] + , , ]> >>> AuthorFormSet = modelformset_factory(Author, fields=('name',), max_num=1) >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name')) diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py index 02a841f5ef..5edd1c722f 100644 --- a/tests/fixtures_regress/tests.py +++ b/tests/fixtures_regress/tests.py @@ -800,11 +800,12 @@ class NaturalKeyFixtureTests(TestCase): verbosity=0, ) books = Book.objects.all() - self.assertEqual( - books.__repr__(), - "[, " - ", " - "]" + self.assertQuerysetEqual( + books, [ + "", + "", + "", + ] ) diff --git a/tests/null_queries/tests.py b/tests/null_queries/tests.py index 8c8ca3f28d..3ba307d397 100644 --- a/tests/null_queries/tests.py +++ b/tests/null_queries/tests.py @@ -47,7 +47,7 @@ class NullQueriesTests(TestCase): # Related managers use __exact=None implicitly if the object hasn't been saved. p2 = Poll(question="How?") - self.assertEqual(repr(p2.choice_set.all()), '[]') + self.assertEqual(repr(p2.choice_set.all()), '') def test_reverse_relations(self): """ diff --git a/tests/string_lookup/tests.py b/tests/string_lookup/tests.py index 13a4544604..5f9d519bf5 100644 --- a/tests/string_lookup/tests.py +++ b/tests/string_lookup/tests.py @@ -78,7 +78,9 @@ class StringLookupTests(TestCase): """ a = Article(name='IP test', text='The body', submitted_from='192.0.2.100') a.save() - self.assertEqual(repr(Article.objects.filter(submitted_from__contains='192.0.2')), - repr([a])) + self.assertQuerysetEqual( + Article.objects.filter(submitted_from__contains='192.0.2'), + [a], lambda x: x + ) # Test that the searches do not match the subnet mask (/32 in this case) self.assertEqual(Article.objects.filter(submitted_from__contains='32').count(), 0)