| | 2155 | Be careful with ``related_name`` |
|---|
| | 2156 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| | 2157 | |
|---|
| | 2158 | If you are using the ``related_name`` attribute on a ``ForeignKey`` or |
|---|
| | 2159 | ``ManyToManyField``, you must always specify a *unique* reverse name for the |
|---|
| | 2160 | field. This would normally cause a problem in abstract base classes, since the |
|---|
| | 2161 | fields on this class are included into each of the child classes, with exactly |
|---|
| | 2162 | the same values for the attributes (including ``related_name``) each time. |
|---|
| | 2163 | |
|---|
| | 2164 | To work around this problem, when you are using ``related_name`` in an |
|---|
| | 2165 | abstract base class (only), part of the name should be the string |
|---|
| | 2166 | ``'%(class)s'``. This is replaced by the lower-cased name of the child class |
|---|
| | 2167 | that the field is used in. Since each class has a different name, each related |
|---|
| | 2168 | name will end up being different. For example:: |
|---|
| | 2169 | |
|---|
| | 2170 | class Base(models.Model): |
|---|
| | 2171 | m2m = models.ManyToMany(OtherModel, related_name="%(class)s_related") |
|---|
| | 2172 | |
|---|
| | 2173 | class Meta: |
|---|
| | 2174 | abstract = True |
|---|
| | 2175 | |
|---|
| | 2176 | class ChildA(Base): |
|---|
| | 2177 | pass |
|---|
| | 2178 | |
|---|
| | 2179 | class ChildB(Base): |
|---|
| | 2180 | pass |
|---|
| | 2181 | |
|---|
| | 2182 | The reverse name of the ``ChildA.m2m`` field will be ``childa_related``, |
|---|
| | 2183 | whilst the reverse name of the ``ChildB.m2m`` field will be |
|---|
| | 2184 | ``childb_related``. It is up to you how you use the ``'%(class)s'`` portion to |
|---|
| | 2185 | construct your related name, but if you forget to use it, Django will raise |
|---|
| | 2186 | errors when you validate your models (or run ``syncdb``). |
|---|
| | 2187 | |
|---|