#33809: ValueError in migrations using apps.get_model for a ForeignKey
--------------------------------------+------------------------
               Reporter:  Jesse       |          Owner:  nobody
                   Type:  Bug         |         Status:  new
              Component:  Migrations  |        Version:  4.0
               Severity:  Normal      |       Keywords:
           Triage Stage:  Unreviewed  |      Has patch:  0
    Needs documentation:  0           |    Needs tests:  0
Patch needs improvement:  0           |  Easy pickings:  0
                  UI/UX:  0           |
--------------------------------------+------------------------
 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.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/33809>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/010701819d4b1fcd-3dac9eba-3eb2-42fa-8ec9-83109488e718-000000%40eu-central-1.amazonses.com.

Reply via email to