Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add missing imports and models to the examples in the the model layer…

… documentation
  • Loading branch information...
commit e4591debd19361e628317e936ed8123d9897dd6a 1 parent d5ce2ff
Marc Egli authored May 18, 2013
10  docs/ref/models/fields.txt
@@ -97,6 +97,8 @@ second element is the human-readable name. For example::
97 97
 Generally, it's best to define choices inside a model class, and to
98 98
 define a suitably-named constant for each value::
99 99
 
  100
+    from django.db import models
  101
+
100 102
     class Student(models.Model):
101 103
         FRESHMAN = 'FR'
102 104
         SOPHOMORE = 'SO'
@@ -994,12 +996,15 @@ relationship with itself -- use ``models.ForeignKey('self')``.
994 996
 If you need to create a relationship on a model that has not yet been defined,
995 997
 you can use the name of the model, rather than the model object itself::
996 998
 
  999
+    from django.db import models
  1000
+
997 1001
     class Car(models.Model):
998 1002
         manufacturer = models.ForeignKey('Manufacturer')
999 1003
         # ...
1000 1004
 
1001 1005
     class Manufacturer(models.Model):
1002 1006
         # ...
  1007
+        pass
1003 1008
 
1004 1009
 To refer to models defined in another application, you can explicitly specify
1005 1010
 a model with the full application label. For example, if the ``Manufacturer``
@@ -1132,6 +1137,9 @@ The possible values for :attr:`~ForeignKey.on_delete` are found in
1132 1137
     necessary to avoid executing queries at the time your models.py is
1133 1138
     imported::
1134 1139
 
  1140
+        from django.db import models
  1141
+        from django.contrib.auth.models import User
  1142
+
1135 1143
         def get_sentinel_user():
1136 1144
             return User.objects.get_or_create(username='deleted')[0]
1137 1145
 
@@ -1204,6 +1212,8 @@ that control how the relationship functions.
1204 1212
     Only used in the definition of ManyToManyFields on self. Consider the
1205 1213
     following model::
1206 1214
 
  1215
+        from django.db import models
  1216
+
1207 1217
         class Person(models.Model):
1208 1218
             friends = models.ManyToManyField("self")
1209 1219
 
10  docs/ref/models/instances.txt
@@ -34,6 +34,8 @@ that, you need to :meth:`~Model.save()`.
34 34
 
35 35
     1. Add a classmethod on the model class::
36 36
 
  37
+        from django.db import models
  38
+
37 39
         class Book(models.Model):
38 40
             title = models.CharField(max_length=100)
39 41
 
@@ -105,6 +107,7 @@ individually.
105 107
 You'll need to call ``full_clean`` manually when you want to run one-step model
106 108
 validation for your own manually created models. For example::
107 109
 
  110
+    from django.core.exceptions import ValidationError
108 111
     try:
109 112
         article.full_clean()
110 113
     except ValidationError as e:
@@ -132,6 +135,7 @@ automatically provide a value for a field, or to do validation that requires
132 135
 access to more than a single field::
133 136
 
134 137
     def clean(self):
  138
+        import datetime
135 139
         from django.core.exceptions import ValidationError
136 140
         # Don't allow draft entries to have a pub_date.
137 141
         if self.status == 'draft' and self.pub_date is not None:
@@ -434,6 +438,8 @@ representation of the model from the ``__unicode__()`` method.
434 438
 
435 439
 For example::
436 440
 
  441
+    from django.db import models
  442
+
437 443
     class Person(models.Model):
438 444
         first_name = models.CharField(max_length=50)
439 445
         last_name = models.CharField(max_length=50)
@@ -460,6 +466,9 @@ Thus, you should return a nice, human-readable string for the object's
460 466
 The previous :meth:`~Model.__unicode__()` example could be similarly written
461 467
 using ``__str__()`` like this::
462 468
 
  469
+    from django.db import models
  470
+    from django.utils.encoding import force_bytes
  471
+
463 472
     class Person(models.Model):
464 473
         first_name = models.CharField(max_length=50)
465 474
         last_name = models.CharField(max_length=50)
@@ -490,6 +499,7 @@ function is usually the best approach.)
490 499
 For example::
491 500
 
492 501
     def get_absolute_url(self):
  502
+        from django.core.urlresolvers import reverse
493 503
         return reverse('people.views.details', args=[str(self.id)])
494 504
 
495 505
 One place Django uses ``get_absolute_url()`` is in the admin app. If an object
6  docs/ref/models/options.txt
@@ -145,6 +145,12 @@ Django quotes column and table names behind the scenes.
145 145
     and a question has more than one answer, and the order of answers matters, you'd
146 146
     do this::
147 147
 
  148
+        from django.db import models
  149
+
  150
+        class Question(models.Model):
  151
+            text = models.TextField()
  152
+            # ...
  153
+
148 154
         class Answer(models.Model):
149 155
             question = models.ForeignKey(Question)
150 156
             # ...
7  docs/ref/models/querysets.txt
@@ -232,6 +232,7 @@ the model field that is being aggregated.
232 232
 For example, if you were manipulating a list of blogs, you may want
233 233
 to determine how many entries have been made in each blog::
234 234
 
  235
+    >>> from django.db.models import Count
235 236
     >>> q = Blog.objects.annotate(Count('entry'))
236 237
     # The name of the first blog
237 238
     >>> q[0].name
@@ -699,6 +700,8 @@ And here's ``select_related`` lookup::
699 700
 ``select_related()`` follows foreign keys as far as possible. If you have the
700 701
 following models::
701 702
 
  703
+    from django.db import models
  704
+
702 705
     class City(models.Model):
703 706
         # ...
704 707
         pass
@@ -814,6 +817,8 @@ that are supported by ``select_related``. It also supports prefetching of
814 817
 
815 818
 For example, suppose you have these models::
816 819
 
  820
+    from django.db import models
  821
+
817 822
     class Topping(models.Model):
818 823
         name = models.CharField(max_length=30)
819 824
 
@@ -1565,6 +1570,7 @@ aggregated.
1565 1570
 For example, when you are working with blog entries, you may want to know the
1566 1571
 number of authors that have contributed blog entries::
1567 1572
 
  1573
+    >>> from django.db.models import Count
1568 1574
     >>> q = Blog.objects.aggregate(Count('entry'))
1569 1575
     {'entry__count': 16}
1570 1576
 
@@ -2042,6 +2048,7 @@ Range test (inclusive).
2042 2048
 
2043 2049
 Example::
2044 2050
 
  2051
+    import datetime
2045 2052
     start_date = datetime.date(2005, 1, 1)
2046 2053
     end_date = datetime.date(2005, 3, 31)
2047 2054
     Entry.objects.filter(pub_date__range=(start_date, end_date))
8  docs/ref/models/relations.txt
@@ -12,8 +12,11 @@ Related objects reference
12 12
     * The "other side" of a :class:`~django.db.models.ForeignKey` relation.
13 13
       That is::
14 14
 
  15
+            from django.db import models
  16
+
15 17
             class Reporter(models.Model):
16  
-                ...
  18
+                # ...
  19
+                pass
17 20
 
18 21
             class Article(models.Model):
19 22
                 reporter = models.ForeignKey(Reporter)
@@ -24,7 +27,8 @@ Related objects reference
24 27
     * Both sides of a :class:`~django.db.models.ManyToManyField` relation::
25 28
 
26 29
             class Topping(models.Model):
27  
-                ...
  30
+                # ...
  31
+                pass
28 32
 
29 33
             class Pizza(models.Model):
30 34
                 toppings = models.ManyToManyField(Topping)
40  docs/topics/db/aggregation.txt
@@ -18,27 +18,29 @@ used to track the inventory for a series of online bookstores:
18 18
 
19 19
 .. code-block:: python
20 20
 
  21
+    from django.db import models
  22
+
21 23
     class Author(models.Model):
22  
-       name = models.CharField(max_length=100)
23  
-       age = models.IntegerField()
  24
+        name = models.CharField(max_length=100)
  25
+        age = models.IntegerField()
24 26
 
25 27
     class Publisher(models.Model):
26  
-       name = models.CharField(max_length=300)
27  
-       num_awards = models.IntegerField()
  28
+        name = models.CharField(max_length=300)
  29
+        num_awards = models.IntegerField()
28 30
 
29 31
     class Book(models.Model):
30  
-       name = models.CharField(max_length=300)
31  
-       pages = models.IntegerField()
32  
-       price = models.DecimalField(max_digits=10, decimal_places=2)
33  
-       rating = models.FloatField()
34  
-       authors = models.ManyToManyField(Author)
35  
-       publisher = models.ForeignKey(Publisher)
36  
-       pubdate = models.DateField()
  32
+        name = models.CharField(max_length=300)
  33
+        pages = models.IntegerField()
  34
+        price = models.DecimalField(max_digits=10, decimal_places=2)
  35
+        rating = models.FloatField()
  36
+        authors = models.ManyToManyField(Author)
  37
+        publisher = models.ForeignKey(Publisher)
  38
+        pubdate = models.DateField()
37 39
 
38 40
     class Store(models.Model):
39  
-       name = models.CharField(max_length=300)
40  
-       books = models.ManyToManyField(Book)
41  
-       registered_users = models.PositiveIntegerField()
  41
+        name = models.CharField(max_length=300)
  42
+        books = models.ManyToManyField(Book)
  43
+        registered_users = models.PositiveIntegerField()
42 44
 
43 45
 Cheat sheet
44 46
 ===========
@@ -123,7 +125,7 @@ If you want to generate more than one aggregate, you just add another
123 125
 argument to the ``aggregate()`` clause. So, if we also wanted to know
124 126
 the maximum and minimum price of all books, we would issue the query::
125 127
 
126  
-    >>> from django.db.models import Avg, Max, Min, Count
  128
+    >>> from django.db.models import Avg, Max, Min
127 129
     >>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
128 130
     {'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}
129 131
 
@@ -148,6 +150,7 @@ the number of authors:
148 150
 .. code-block:: python
149 151
 
150 152
     # Build an annotated queryset
  153
+    >>> from django.db.models import Count
151 154
     >>> q = Book.objects.annotate(Count('authors'))
152 155
     # Interrogate the first object in the queryset
153 156
     >>> q[0]
@@ -192,6 +195,7 @@ and aggregate the related value.
192 195
 For example, to find the price range of books offered in each store,
193 196
 you could use the annotation::
194 197
 
  198
+    >>> from django.db.models import Max, Min
195 199
     >>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))
196 200
 
197 201
 This tells Django to retrieve the ``Store`` model, join (through the
@@ -222,7 +226,7 @@ For example, we can ask for all publishers, annotated with their respective
222 226
 total book stock counters (note how we use ``'book'`` to specify the
223 227
 ``Publisher`` -> ``Book`` reverse foreign key hop)::
224 228
 
225  
-    >>> from django.db.models import Count, Min, Sum, Max, Avg
  229
+    >>> from django.db.models import Count, Min, Sum, Avg
226 230
     >>> Publisher.objects.annotate(Count('book'))
227 231
 
228 232
 (Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute
@@ -269,6 +273,7 @@ constraining the objects for which an annotation is calculated. For example,
269 273
 you can generate an annotated list of all books that have a title starting
270 274
 with "Django" using the query::
271 275
 
  276
+    >>> from django.db.models import Count, Avg
272 277
     >>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors'))
273 278
 
274 279
 When used with an ``aggregate()`` clause, a filter has the effect of
@@ -407,6 +412,8 @@ particularly, when counting things.
407 412
 
408 413
 By way of example, suppose you have a model like this::
409 414
 
  415
+    from django.db import models
  416
+
410 417
     class Item(models.Model):
411 418
         name = models.CharField(max_length=10)
412 419
         data = models.IntegerField()
@@ -457,5 +464,6 @@ For example, if you wanted to calculate the average number of authors per
457 464
 book you first annotate the set of books with the author count, then
458 465
 aggregate that author count, referencing the annotation field::
459 466
 
  467
+    >>> from django.db.models import Count, Avg
460 468
     >>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))
461 469
     {'num_authors__avg': 1.66}
22  docs/topics/db/managers.txt
@@ -62,6 +62,8 @@ For example, this custom ``Manager`` offers a method ``with_counts()``, which
62 62
 returns a list of all ``OpinionPoll`` objects, each with an extra
63 63
 ``num_responses`` attribute that is the result of an aggregate query::
64 64
 
  65
+    from django.db import models
  66
+
65 67
     class PollManager(models.Manager):
66 68
         def with_counts(self):
67 69
             from django.db import connection
@@ -101,6 +103,8 @@ Modifying initial Manager QuerySets
101 103
 A ``Manager``'s base ``QuerySet`` returns all objects in the system. For
102 104
 example, using this model::
103 105
 
  106
+    from django.db import models
  107
+
104 108
     class Book(models.Model):
105 109
         title = models.CharField(max_length=100)
106 110
         author = models.CharField(max_length=50)
@@ -236,7 +240,7 @@ class, but still customize the default manager. For example, suppose you have
236 240
 this base class::
237 241
 
238 242
     class AbstractBase(models.Model):
239  
-        ...
  243
+        # ...
240 244
         objects = CustomManager()
241 245
 
242 246
         class Meta:
@@ -246,14 +250,15 @@ If you use this directly in a subclass, ``objects`` will be the default
246 250
 manager if you declare no managers in the base class::
247 251
 
248 252
     class ChildA(AbstractBase):
249  
-        ...
  253
+        # ...
250 254
         # This class has CustomManager as the default manager.
  255
+        pass
251 256
 
252 257
 If you want to inherit from ``AbstractBase``, but provide a different default
253 258
 manager, you can provide the default manager on the child class::
254 259
 
255 260
     class ChildB(AbstractBase):
256  
-        ...
  261
+        # ...
257 262
         # An explicit default manager.
258 263
         default_manager = OtherManager()
259 264
 
@@ -274,9 +279,10 @@ it into the inheritance hierarchy *after* the defaults::
274 279
             abstract = True
275 280
 
276 281
     class ChildC(AbstractBase, ExtraManager):
277  
-        ...
  282
+        # ...
278 283
         # Default manager is CustomManager, but OtherManager is
279 284
         # also available via the "extra_manager" attribute.
  285
+        pass
280 286
 
281 287
 Note that while you can *define* a custom manager on the abstract model, you
282 288
 can't *invoke* any methods using the abstract model. That is::
@@ -349,8 +355,7 @@ the manager class::
349 355
 
350 356
     class MyManager(models.Manager):
351 357
         use_for_related_fields = True
352  
-
353  
-        ...
  358
+        # ...
354 359
 
355 360
 If this attribute is set on the *default* manager for a model (only the
356 361
 default manager is considered in these situations), Django will use that class
@@ -396,7 +401,8 @@ it, whereas the following will not work::
396 401
 
397 402
     # BAD: Incorrect code
398 403
     class MyManager(models.Manager):
399  
-        ...
  404
+        # ...
  405
+        pass
400 406
 
401 407
     # Sets the attribute on an instance of MyManager. Django will
402 408
     # ignore this setting.
@@ -404,7 +410,7 @@ it, whereas the following will not work::
404 410
     mgr.use_for_related_fields = True
405 411
 
406 412
     class MyModel(models.Model):
407  
-        ...
  413
+        # ...
408 414
         objects = mgr
409 415
 
410 416
     # End of incorrect code.
50  docs/topics/db/models.txt
@@ -90,6 +90,8 @@ attributes. Be careful not to choose field names that conflict with the
90 90
 
91 91
 Example::
92 92
 
  93
+    from django.db import models
  94
+
93 95
     class Musician(models.Model):
94 96
         first_name = models.CharField(max_length=50)
95 97
         last_name = models.CharField(max_length=50)
@@ -290,8 +292,11 @@ For example, if a ``Car`` model has a ``Manufacturer`` -- that is, a
290 292
 ``Manufacturer`` makes multiple cars but each ``Car`` only has one
291 293
 ``Manufacturer`` -- use the following definitions::
292 294
 
  295
+    from django.db import models
  296
+
293 297
     class Manufacturer(models.Model):
294 298
         # ...
  299
+        pass
295 300
 
296 301
     class Car(models.Model):
297 302
         manufacturer = models.ForeignKey(Manufacturer)
@@ -340,8 +345,11 @@ For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
340 345
 ``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings
341 346
 -- here's how you'd represent that::
342 347
 
  348
+    from django.db import models
  349
+
343 350
     class Topping(models.Model):
344 351
         # ...
  352
+        pass
345 353
 
346 354
     class Pizza(models.Model):
347 355
         # ...
@@ -403,6 +411,8 @@ intermediate model. The intermediate model is associated with the
403 411
 that will act as an intermediary. For our musician example, the code would look
404 412
 something like this::
405 413
 
  414
+    from django.db import models
  415
+
406 416
     class Person(models.Model):
407 417
         name = models.CharField(max_length=128)
408 418
 
@@ -583,6 +593,7 @@ It's perfectly OK to relate a model to one from another app. To do this, import
583 593
 the related model at the top of the file where your model is defined. Then,
584 594
 just refer to the other model class wherever needed. For example::
585 595
 
  596
+    from django.db import models
586 597
     from geography.models import ZipCode
587 598
 
588 599
     class Restaurant(models.Model):
@@ -630,6 +641,8 @@ Meta options
630 641
 
631 642
 Give your model metadata by using an inner ``class Meta``, like so::
632 643
 
  644
+    from django.db import models
  645
+
633 646
     class Ox(models.Model):
634 647
         horn_length = models.IntegerField()
635 648
 
@@ -660,6 +673,8 @@ model.
660 673
 
661 674
 For example, this model has a few custom methods::
662 675
 
  676
+    from django.db import models
  677
+
663 678
     class Person(models.Model):
664 679
         first_name = models.CharField(max_length=50)
665 680
         last_name = models.CharField(max_length=50)
@@ -729,6 +744,8 @@ A classic use-case for overriding the built-in methods is if you want something
729 744
 to happen whenever you save an object. For example (see
730 745
 :meth:`~Model.save` for documentation of the parameters it accepts)::
731 746
 
  747
+    from django.db import models
  748
+
732 749
     class Blog(models.Model):
733 750
         name = models.CharField(max_length=100)
734 751
         tagline = models.TextField()
@@ -740,6 +757,8 @@ to happen whenever you save an object. For example (see
740 757
 
741 758
 You can also prevent saving::
742 759
 
  760
+    from django.db import models
  761
+
743 762
     class Blog(models.Model):
744 763
         name = models.CharField(max_length=100)
745 764
         tagline = models.TextField()
@@ -826,6 +845,8 @@ the child (and Django will raise an exception).
826 845
 
827 846
 An example::
828 847
 
  848
+    from django.db import models
  849
+
829 850
     class CommonInfo(models.Model):
830 851
         name = models.CharField(max_length=100)
831 852
         age = models.PositiveIntegerField()
@@ -854,14 +875,16 @@ attribute. If a child class does not declare its own :ref:`Meta <meta-options>`
854 875
 class, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to
855 876
 extend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::
856 877
 
  878
+    from django.db import models
  879
+
857 880
     class CommonInfo(models.Model):
858  
-        ...
  881
+        # ...
859 882
         class Meta:
860 883
             abstract = True
861 884
             ordering = ['name']
862 885
 
863 886
     class Student(CommonInfo):
864  
-        ...
  887
+        # ...
865 888
         class Meta(CommonInfo.Meta):
866 889
             db_table = 'student_info'
867 890
 
@@ -901,6 +924,8 @@ abstract base class (only), part of the name should contain
901 924
 
902 925
 For example, given an app ``common/models.py``::
903 926
 
  927
+    from django.db import models
  928
+
904 929
     class Base(models.Model):
905 930
         m2m = models.ManyToManyField(OtherModel, related_name="%(app_label)s_%(class)s_related")
906 931
 
@@ -949,6 +974,8 @@ relationship introduces links between the child model and each of its parents
949 974
 (via an automatically-created :class:`~django.db.models.OneToOneField`).
950 975
 For example::
951 976
 
  977
+    from django.db import models
  978
+
952 979
     class Place(models.Model):
953 980
         name = models.CharField(max_length=50)
954 981
         address = models.CharField(max_length=80)
@@ -998,7 +1025,7 @@ If the parent has an ordering and you don't want the child to have any natural
998 1025
 ordering, you can explicitly disable it::
999 1026
 
1000 1027
     class ChildModel(ParentModel):
1001  
-        ...
  1028
+        # ...
1002 1029
         class Meta:
1003 1030
             # Remove parent's ordering effect
1004 1031
             ordering = []
@@ -1061,15 +1088,21 @@ Proxy models are declared like normal models. You tell Django that it's a
1061 1088
 proxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of
1062 1089
 the ``Meta`` class to ``True``.
1063 1090
 
1064  
-For example, suppose you want to add a method to the ``Person`` model described
1065  
-above. You can do it like this::
  1091
+For example, suppose you want to add a method to the ``Person`` model. You can do it like this::
  1092
+
  1093
+    from django.db import models
  1094
+
  1095
+    class Person(models.Model):
  1096
+        first_name = models.CharField(max_length=30)
  1097
+        last_name = models.CharField(max_length=30)
1066 1098
 
1067 1099
     class MyPerson(Person):
1068 1100
         class Meta:
1069 1101
             proxy = True
1070 1102
 
1071 1103
         def do_something(self):
1072  
-            ...
  1104
+            # ...
  1105
+            pass
1073 1106
 
1074 1107
 The ``MyPerson`` class operates on the same database table as its parent
1075 1108
 ``Person`` class. In particular, any new instances of ``Person`` will also be
@@ -1125,8 +1158,11 @@ classes will still be available.
1125 1158
 Continuing our example from above, you could change the default manager used
1126 1159
 when you query the ``Person`` model like this::
1127 1160
 
  1161
+    from django.db import models
  1162
+
1128 1163
     class NewManager(models.Manager):
1129  
-        ...
  1164
+        # ...
  1165
+        pass
1130 1166
 
1131 1167
     class MyPerson(Person):
1132 1168
         objects = NewManager()
2  docs/topics/db/queries.txt
@@ -17,6 +17,8 @@ models, which comprise a Weblog application:
17 17
 
18 18
 .. code-block:: python
19 19
 
  20
+    from django.db import models
  21
+
20 22
     class Blog(models.Model):
21 23
         name = models.CharField(max_length=100)
22 24
         tagline = models.TextField()

0 notes on commit e4591de

Please sign in to comment.
Something went wrong with that request. Please try again.