Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Bi-directional ManyToMany - How to prevent table creation on second model?

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?

like image 494
samurailawngnome Avatar asked Feb 03 '11 00:02

samurailawngnome


2 Answers

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)
like image 127
Lapin-Blanc Avatar answered Oct 19 '22 07:10

Lapin-Blanc


You don't need to put a ManyToManyField on both sides of the relation. Django will do that for you.

You probably want something more like this:

class Model1(models.Model):
    name = models.CharField(max_length=128)
    ...

class Model2(models.Model):
    name = models.CharField(max_length=128)
    othermodels = models.ManyToManyField(Model1, through='Model1Model2')
    ...        

class Membership(models.Model):
    class Meta:
        db_table = 'model1_model2'
    model1 = models.ForeignKey(Model1)        
    model2 = models.ForeignKey(Model2)

When you're working with your models, an instance of Model1 will have a othermodels_set field which is automatically added by django. Instances of Model2 will have othermodels.

like image 34
Seth Avatar answered Oct 19 '22 07:10

Seth