How do I tell Django to not create a table for an M2M related field?

前端 未结 3 1751
粉色の甜心
粉色の甜心 2021-01-16 12:17

I\'m using this little jewel of a Django code snippet to edit a ManyToManyField from both directions:

class ManyToManyField_NoSyncdb(models.ManyToManyField):         


        
3条回答
  •  盖世英雄少女心
    2021-01-16 12:40

    So, if you want to have access to the ManyToMany in both models in the Admin, currently the official solution is to use inlinemodel for the second model. I had also this same problem/need just a few days ago. And I was not really satisfied with the inlinemodel solution (heavy in DB queries if you have a lot of entries, cannot use the filter_horizontal widget, etc.).

    The solution I found (that's working with Django 1.2+ and syncdb) is this:

    class User(models.Model):
        groups = models.ManyToManyField('Group', through='UserGroups')
    
    class Group(models.Model):
        users = models.ManyToManyField('User', through='UserGroups')
    
    class UserGroups(models.Model):
        user_id = models.ForeignKey(User)
        group_id = models.ForeignKey(Group)
    
        class Meta:
            db_table = 'app_user_group'
            auto_created = User
    

    See ticket 897 for more info.

    Unfortunately, if you're using South you will have to remove the creation of the app_user_group table in every migration file created automatically.

提交回复
热议问题