Code

Ticket #10981: 10981-string_model_names_notes.diff

File 10981-string_model_names_notes.diff, 2.2 KB (added by ramiro, 5 years ago)
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,53 @@
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 production.models import Manufacturer
20+
21+    class Vehicle(models.Model):
22+        manufacturer = models.ForeignKey(Manufacturer)
23+        # ...
24+
25+::
26+
27+    # production/models.py
28+    from goods.models import Vehicle # This would introduce circular imports
29+
30+    class Manufacturer(models.Model):
31+        main_product = models.ForeignKey(Vehicle)
32+
33+Solving this by using Python imports would mean having circular imports between
34+the models files of both applications. That's the reason why, in this particular
35+case, you can use the name of a model in string form::
36+
37+    # goods/models.py
38+    from production.models import Manufacturer
39+
40+    class Vehicle(models.Model):
41+        manufacturer = models.ForeignKey(Manufacturer)
42+        # ...
43+
44+::
45+
46+    # production/models.py
47+
48+    class Manufacturer(models.Model):
49+        main_product = models.ForeignKey('goods.Vehicle')
50 
51 .. versionchanged:: 1.0
52    Refering models in other applications must include the application label.
53 
54-To refer to models defined in another
55-application, you must instead explicitly specify the application label. For
56-example, if the ``Manufacturer`` model above is defined in another application
57-called ``production``, you'd need to use::
58+To refer to models defined in another application, you must instead explicitly
59+specify the application label. For example, if the ``Manufacturer`` model above
60+is defined in another application called ``production``, you'd need to use::
61 
62     class Car(models.Model):
63         manufacturer = models.ForeignKey('production.Manufacturer')