Ticket #10981: 10981-string_model_names_notes.diff

File 10981-string_model_names_notes.diff, 2.2 KB (added by ramiro, 6 years ago)
  • docs/ref/models/fields.txt

    diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt
    a b  
    801801        # ...
    802802
    803803Note, however, that this only refers to models in the same ``models.py`` file --
    804 you cannot use a string to reference a model defined in another application or
    805 imported from elsewhere.
     804As a general rule, you cannot use a string to reference a model defined in
     805another application or imported from elsewhere.
     806
     807.. versionchanged:: 1.0
     808
     809The only exception to this rule is the following scenario: Models defined in
     810different 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
     827Solving this by using Python imports would mean having circular imports between
     828the models files of both applications. That's the reason why, in this particular
     829case, 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')
    806844
    807845.. versionchanged:: 1.0
    808846   Refering models in other applications must include the application label.
    809847
    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::
     848To refer to models defined in another application, you must instead explicitly
     849specify the application label. For example, if the ``Manufacturer`` model above
     850is defined in another application called ``production``, you'd need to use::
    814851
    815852    class Car(models.Model):
    816853        manufacturer = models.ForeignKey('production.Manufacturer')
Back to Top