19

I have a simple django model with a ForeignKey

class FooModel(models.Model):
    foo = models.ForeignKey('Foo', related_name="foo_choices")
    bar = models.CharField(max_length=50)

The related_name attribute exists already, but I'd like to change it. Will this change require a migration of any kind? When I run the schemamigration management command after modifying the related_name I get the "Nothing seems to have changed" but I wanted to verify.

Toran Billups
  • 27,111
  • 40
  • 155
  • 268

2 Answers2

15

No You do not need a migration.

Related name is the name to use for the relation from the related object back to this one (the reverse relationship).

related_name has nothing to do with the database. It is consumed by the Django's ORM to fetch queryset results, so you dont need a migration if you change the related_name attribute on a models' field.

Some additional documentation here on the usage of related_name

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 5
    Then why does Django create a migration file when related_name changes? – Marshall X Oct 19 '17 at 23:22
  • 2
    @MarshallX This ticket may shed light on your question https://code.djangoproject.com/ticket/25601 . But I am still wonder there is a way to mark such migrations should not emit any sql(sqlmigrate) when only related_name is changed. – schemacs Dec 28 '17 at 07:29
  • here is the code first drop: https://github.com/django/django/blob/f3a98224e6dd5f8846008512f281e452dc3b1909/django/db/backends/base/schema.py#L514 then rebuild: https://github.com/django/django/blob/f3a98224e6dd5f8846008512f281e452dc3b1909/django/db/backends/base/schema.py#L734 – schemacs Dec 28 '17 at 09:51
  • This answer is clearly wrong! Yes, you need a migration. MigrationAutodetector will detect a migration. – dbow Mar 08 '21 at 12:12
11

The above accepted answer is now outdated.

Django does create and alter field foreign_key_field on model migration when the related name of a foreign key field changes.

Raunaqss
  • 1,265
  • 12
  • 17
  • I believe it also causes, at least in MySQL, a DROP INDEX and then CREATE INDEX statement. There's an issue open in Django's issue tracker about this. https://code.djangoproject.com/ticket/25253 – Adam Easterling Aug 13 '20 at 19:25