Django migrations RunPython not able to call model methods

前端 未结 4 468
感情败类
感情败类 2020-12-04 23:04

I\'m creating a data migration using the RunPython method. However when I try to run a method on the object none are defined. Is it possible to call a method de

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 00:11

    did you call your model like said in the documentation ?

    def combine_names(apps, schema_editor):
        # We can't import the Person model directly as it may be a newer
        # version than this migration expects. We use the historical version.
        Person = apps.get_model("yourappname", "Person")
        for person in Person.objects.all():
            person.name = "%s %s" % (person.first_name, person.last_name)
            person.save()
    

    Data-Migration Because at this point, you can't import your Model directly :

    from yourappname.models import Person
    

    Update

    The internal Django code is in this file django/db/migrations/state.py django.db.migrations.state.ModelState#construct_fields

    def construct_fields(self):
        "Deep-clone the fields using deconstruction"
        for name, field in self.fields:
            _, path, args, kwargs = field.deconstruct()
            field_class = import_string(path)
            yield name, field_class(*args, **kwargs)
    

    There is only fields that are clones in a "fake" model instance:

    MyModel.__module__ = '__fake__'
    

    Github Django

提交回复
热议问题