Code

Ticket #10981: 10981-string_model_names_notes.2.diff

File 10981-string_model_names_notes.2.diff, 2.5 KB (added by ramiro, 5 years ago)

New corrected and sllightly enhanced iteration

Line 
1diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt
2--- a/docs/ref/models/fields.txt
3+++ b/docs/ref/models/fields.txt
4@@ -801,16 +801,58 @@
5         # ...
6 
7 Note, however, that this only refers to models in the same ``models.py`` file --
8-you cannot use a string to reference a model defined in another application or
9-imported from elsewhere.
10+As a general rule, you cannot use a string to reference a model defined in
11+another application or imported from elsewhere.
12+
13+.. versionchanged:: 1.0
14+
15+The only exception to this rule is the following scenario: Models defined in
16+different applications have mutually referencing relationships::
17+
18+    # goods/models.py
19+    from django.db import models
20+    from production.models import Manufacturer
21+
22+    class Vehicle(models.Model):
23+        manufacturer = models.ForeignKey(Manufacturer)
24+        # ...
25+
26+::
27+
28+    # production/models.py
29+    from django.db import models
30+    from goods.models import Vehicle # This would introduce circular imports
31+
32+    class Manufacturer(models.Model):
33+        main_product = models.ForeignKey(Vehicle, related_name='lead_manufacturers')
34+
35+Using Python imports in this case would introduce circular imports between the
36+models files of both applications and this would keep them from working. That's
37+the reason why, in this particular case, you can use the name of a model in
38+string form to break the import loop::
39+
40+    # goods/models.py
41+    from django.db import models
42+    from production.models import Manufacturer
43+
44+    class Vehicle(models.Model):
45+        manufacturer = models.ForeignKey(Manufacturer)
46+        # ...
47+
48+::
49+
50+    # production/models.py
51+    from django.db import models
52+
53+    class Manufacturer(models.Model):
54+        main_product = models.ForeignKey('goods.Vehicle', related_name='lead_manufacturers')
55 
56 .. versionchanged:: 1.0
57    Refering models in other applications must include the application label.
58 
59-To refer to models defined in another
60-application, you must instead explicitly specify the application label. For
61-example, if the ``Manufacturer`` model above is defined in another application
62-called ``production``, you'd need to use::
63+To refer to models defined in another application, you must instead explicitly
64+specify the application label. For example, if the ``Manufacturer`` model above
65+is defined in another application called ``production``, you'd need to use::
66 
67     class Car(models.Model):
68         manufacturer = models.ForeignKey('production.Manufacturer')