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 django.db import models |
| 814 | from production.models import Manufacturer |
| 815 | |
| 816 | class Vehicle(models.Model): |
| 817 | manufacturer = models.ForeignKey(Manufacturer) |
| 818 | # ... |
| 819 | |
| 820 | :: |
| 821 | |
| 822 | # production/models.py |
| 823 | from django.db import models |
| 824 | from goods.models import Vehicle # This would introduce circular imports |
| 825 | |
| 826 | class Manufacturer(models.Model): |
| 827 | main_product = models.ForeignKey(Vehicle, related_name='lead_manufacturers') |
| 828 | |
| 829 | Using Python imports in this case would introduce circular imports between the |
| 830 | models files of both applications and this would keep them from working. That's |
| 831 | the reason why, in this particular case, you can use the name of a model in |
| 832 | string form to break the import loop:: |
| 833 | |
| 834 | # goods/models.py |
| 835 | from django.db import models |
| 836 | from production.models import Manufacturer |
| 837 | |
| 838 | class Vehicle(models.Model): |
| 839 | manufacturer = models.ForeignKey(Manufacturer) |
| 840 | # ... |
| 841 | |
| 842 | :: |
| 843 | |
| 844 | # production/models.py |
| 845 | from django.db import models |
| 846 | |
| 847 | class Manufacturer(models.Model): |
| 848 | main_product = models.ForeignKey('goods.Vehicle', related_name='lead_manufacturers') |
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:: |
| 853 | To refer to models defined in another application, you must instead explicitly |
| 854 | specify the application label. For example, if the ``Manufacturer`` model above |
| 855 | is defined in another application called ``production``, you'd need to use:: |