Repository: klen/peewee_migrate

Issue:
Bug report: Self foreign keys are not handled
**Describe the bug**
After creating the migration with the model containing foreign key to itself, migration is failing due to `KeyError`. After quick investigation, the exact line containing the bug is `ForeignKeyField(model=migrator.orm["model"], ...)`. During execution of this code, `"model"` is not yet added to `migrator.orm` dict. Instead, the call should look like: `ForeignKeyField(model="self", ...)`. After changing it the proposed way, migration has completed successfully.

**To Reproduce**
Steps to reproduce the behavior:
1. Write a model containing a self-referencing foreign key:
```python
class TestModel(Model):
    parent = ForeignKeyField("self")
```
2. Create a migration
3. Run the migration

**Expected behavior**
Migration should pass correctly.

**Desktop (please complete the following information):**
 - Version 1.4.2


Discussion:

Patch:
diff --git a/peewee_migrate/auto.py b/peewee_migrate/auto.py
index cab9f2a..a71ff4b 100644
--- a/peewee_migrate/auto.py
+++ b/peewee_migrate/auto.py
@@ -67,7 +67,11 @@ class Column(VanilaColumn):
         if isinstance(field, pw.ForeignKeyField):
             self.to_field = field.rel_field.name
             self.related_name = field.backref
-            self.rel_model = "migrator.orm['%s']" % field.rel_model._meta.table_name
+            self.rel_model = (
+                "'self'"
+                if field.rel_model == field.model
+                else "migrator.orm['%s']" % field.rel_model._meta.table_name
+            )
 
     def get_field(self, space=' '):
         # Generate the field definition for this column.


Test patch:
diff --git a/tests/test_auto.py b/tests/test_auto.py
index 5123aa5..2065bc8 100644
--- a/tests/test_auto.py
+++ b/tests/test_auto.py
@@ -95,3 +95,28 @@ def test_auto_multi_column_index():
     code = model_to_code(Object)
     assert code
     assert "indexes = [(('first_name', 'last_name'), True)]" in code
+
+
+def test_self_referencing_foreign_key_on_model_create():
+    from peewee_migrate.auto import field_to_code
+
+    class Employee(pw.Model):
+        manager = pw.ForeignKeyField("self")
+
+    code = field_to_code(Employee.manager)
+    assert "model='self'" in code
+
+
+def test_self_referencing_foreign_key_on_field_added():
+    from peewee_migrate.auto import diff_one
+
+    class Employee(pw.Model):
+        name = pw.CharField()
+
+    class EmployeeNew(pw.Model):
+        name = pw.CharField()
+        manager = pw.ForeignKeyField("self")
+
+    changes = diff_one(EmployeeNew, Employee)
+    assert "migrator.add_fields" in changes[0]
+    assert "model='self'" in changes[0]