Opened 7 months ago

Last modified 6 months ago

#28987 assigned Bug

Migration changing ManyToManyField target to 'self' doesn't work correctly

Reported by: MSleepyPanda Owned by: SShayashi
Component: Migrations Version: 2.0
Severity: Normal Keywords: ManyToManyField
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: yes Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Steps to reproduce:
Create Models:

class Bar(models.Model):
    pass

class Foo(models.Model):
    bar = models.ManyToManyField('Bar', blank=True)

Migrate:

./manage.py makemigrations app
./manage.py migrate

Change type of the ManyToManyField to Foo:

class Bar(models.Model):
    pass

class Foo(models.Model):
    bar = models.ManyToManyField('Foo', blank=True)

Migrate (see above)

In the admin page, navigate to "add Foo", click save

You should see an OperationalError, "no such column: app_foo_bar.from_foo_id"

Change History (4)

comment:1 Changed 7 months ago by Tim Graham

Summary: makemigrations doesn't catch ManyToManyField type change, leaves DB in inconsistent stateMigration changing ManyToManyField target to 'self' doesn't work correctly
Triage Stage: UnreviewedAccepted

I believe it works correctly as long as the new target model isn't 'self'.

comment:2 Changed 6 months ago by SShayashi

Needs tests: set
Owner: changed from nobody to SShayashi
Status: newassigned

comment:3 Changed 6 months ago by SShayashi

Can I check out what you want? You can use 'self' instead of 'Foo' like this :

class Foo(models.Model):
    bar = models.ManyToManyField('self', blank=True)

You meant that we should use 'Foo' rather than 'self', right?

comment:4 in reply to:  3 Changed 6 months ago by MSleepyPanda

Replying to SShayashi:

Can I check out what you want? You can use 'self' instead of 'Foo' like this :

class Foo(models.Model):
    bar = models.ManyToManyField('self', blank=True)

You meant that we should use 'Foo' rather than 'self', right?

Exactly, though i wasn't aware that self would work in that context. I think i like naming the type directly more, since self could be easily confused with the self argument of class methods.

Note: See TracTickets for help on using tickets.
Back to Top