问题描述
我有两个模型,每个都有一个共享的ManyToMany,使用db_table字段。但是如何防止syncdb尝试创建第二个模型的共享表? class Model1(models.Model) :
othermodels = ManyToManyField('Model2',db_table ='model1_model2',related_name ='model1_model2')
class Model2(models.model):
othermodels = ManyToManyField Model1',db_table ='model1_model2',related_name ='model2_model1')
环境,因为一些表被创造了零碎,因为我全部建成。但是从一个空数据库中,syncdb会抛出:
_mysql_exceptions.OperationalError:(1050,Tablemodel1_model2已经存在)
从第二个模型的字段丢失,以防止重复的表创建?或者我只是这样做完全错误?
我还发现了这个解决方案,对我来说非常适用:
class Test1(models.Model):
/ pre>
tests2 = models.ManyToManyField('Test2',blank = True)
class Test2(models.Model):
tests1 = models.ManyToManyField('Test1',through = Test1.tests2.through,blank = True)
I have two models, each has a shared ManyToMany, using the db_table field. But how do I prevent syncdb from attempting to create the shared table, for the second model?
class Model1(models.Model): othermodels = ManyToManyField('Model2', db_table='model1_model2', related_name='model1_model2') class Model2(models.model): othermodels = ManyToManyField('Model1', db_table='model1_model2', related_name='model2_model1')
It's working great in my dev environment, because some of the tables got created piecemeal, as I built it all out. But from an empty database, syncdb throws: _mysql_exceptions.OperationalError: (1050, "Table 'model1_model2' already exists")
Is there a flag that I'm missing from the second model's field to prevent duplicate table creation? Or am I just doing this entirely wrong?
解决方案I also found this solution, which worked perfectly for me :
class Test1(models.Model): tests2 = models.ManyToManyField('Test2', blank=True) class Test2(models.Model): tests1 = models.ManyToManyField('Test1', through=Test1.tests2.through, blank=True)
这篇关于Django双向ManyToMany - 如何防止在第二个模型上创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!