804 | | you cannot use a string to reference a model defined in another application or |
805 | | imported from elsewhere. |
| 804 | As a general rule, you cannot use a string to reference a model defined in |
| 805 | another application or imported from elsewhere. |
| 806 | |
| 807 | .. versionchanged:: 1.0 |
| 808 | |
| 809 | The only exception to this rule is the following scenario: Models defined in |
| 810 | different applications have mutually referencing relationships:: |
| 811 | |
| 812 | # goods/models.py |
| 813 | from production.models import Manufacturer |
| 814 | |
| 815 | class Vehicle(models.Model): |
| 816 | manufacturer = models.ForeignKey(Manufacturer) |
| 817 | # ... |
| 818 | |
| 819 | :: |
| 820 | |
| 821 | # production/models.py |
| 822 | from goods.models import Vehicle # This would introduce circular imports |
| 823 | |
| 824 | class Manufacturer(models.Model): |
| 825 | main_product = models.ForeignKey(Vehicle) |
| 826 | |
| 827 | Solving this by using Python imports would mean having circular imports between |
| 828 | the models files of both applications. That's the reason why, in this particular |
| 829 | case, you can use the name of a model in string form:: |
| 830 | |
| 831 | # goods/models.py |
| 832 | from production.models import Manufacturer |
| 833 | |
| 834 | class Vehicle(models.Model): |
| 835 | manufacturer = models.ForeignKey(Manufacturer) |
| 836 | # ... |
| 837 | |
| 838 | :: |
| 839 | |
| 840 | # production/models.py |
| 841 | |
| 842 | class Manufacturer(models.Model): |
| 843 | main_product = models.ForeignKey('goods.Vehicle') |
810 | | To refer to models defined in another |
811 | | application, you must instead explicitly specify the application label. For |
812 | | example, if the ``Manufacturer`` model above is defined in another application |
813 | | called ``production``, you'd need to use:: |
| 848 | To refer to models defined in another application, you must instead explicitly |
| 849 | specify the application label. For example, if the ``Manufacturer`` model above |
| 850 | is defined in another application called ``production``, you'd need to use:: |