Opened 2 years ago

Closed 2 years ago

Last modified 2 years ago

#33809 closed Bug (needsinfo)

ValueError in migrations using apps.get_model() for a ForeignKey.

Reported by: Jesse Owned by: nobody
Component: Migrations Version: 4.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Django 4.0.5, Python 3.9.5

I believe this is a regression of https://code.djangoproject.com/ticket/24282

Snippet of the stack trace:

  File "/home/.../venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/.../venv/lib/python3.9/site-packages/django/db/models/query.py", line 512, in create
    obj = self.model(**kwargs)
  File "/home/.../venv/lib/python3.9/site-packages/django/db/models/base.py", line 541, in __init__
    _setattr(self, field.name, rel_obj)
  File "/home/.../venv/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 235, in __set__
    raise ValueError(
ValueError: Cannot assign "<Foo: Foo object (...)>": "Bar.foo" must be a "Foo" instance.

This error is coming from a RunPython() function. It's using a model from apps.get_model(), querying a model instance, and then using that instance in a ForeignKey field. I assume the error is because the type from apps.get_model() isn't the same as the actual model class.

Essentially this is what it's doing:

def custom_migration_func(apps, schema_editor):
    Foo = apps.get_model("foo", "Foo")
    Bar = apps.get_model("bar", "Bar")

    for foo in Foo.objects.all():
        Bar.objects.create(foo=foo)  # breaks here

I was able to workaround this by setting the ID directly:

Bar.objects.create(foo_id=foo.pk)

If adding support for this isn't feasible, the documentation should at least be updated to address this. I wasn't able to find any information regarding this in the docs.

Attachments (1)

ticket_33809.zip (14.1 KB ) - added by Mariusz Felisiak 2 years ago.

Download all attachments as: .zip

Change History (2)

comment:1 by Mariusz Felisiak, 2 years ago

Resolution: needsinfo
Status: newclosed
Summary: ValueError in migrations using apps.get_model for a ForeignKeyValueError in migrations using apps.get_model() for a ForeignKey.

Thanks for the report, however it works for me (I attached the test project). We also have a regression test that covers this use case.

Please reopen the ticket if you can debug your issue and provide a sample project that reproduces it.

Last edited 2 years ago by Mariusz Felisiak (previous) (diff)

by Mariusz Felisiak, 2 years ago

Attachment: ticket_33809.zip added
Note: See TracTickets for help on using tickets.
Back to Top