Adding a “through” table to django field and migrating with South?

后端 未结 3 1920
-上瘾入骨i
-上瘾入骨i 2021-01-04 01:41

Seems like this should be \"easy\" or at least documented somewhere, I just cant find it.

Lets say I have a model:

class A(models.Model):
    users =         


        
3条回答
  •  [愿得一人]
    2021-01-04 02:11

    You should be able to do this pretty easily.

    First of all, make sure that the manual through table that you are creating has the same table name in the database as the one Django originally created automatically.

    So, first, let's consider a manual through model before your change:

    class AUsers(models.Model):
        user = models.ForeignKey('auth.User')
        a = models.ForeignKey('A')
    
        class Meta:
            db_table = 'appname_a_user'
    

    That should be functionally (almost) identical to the ManyToManyField you used to have. Actually, you could make an empty migration and apply it, and then use --auto for your changes (but don't).

    Now, add your field like you did in your sample code above, and then run ./manage.py schemamigration appname manual_through_table --empty. That will give you an empty migration named ####_manual_through_table.py.

    In the migration itself, there will be a forwards and backwards method. Each one needs to be one line each:

    def forwards(self, orm):
        db.add_column('appname_a_user', 'new_field', self.gf('django.db.models.fields.BooleanField')(default=False))
    
    def backwards(self, orm):
        db.delete_column('appname_a_user', 'new_field')
    

    That should get you what you are after.

提交回复
热议问题