0

I have found in internet different examples on how to handle m2m relations with existing DB models, such as ex1 or here ex2, however I'm still not able to solve the error I get. My models are depicted below. Basically, all the tables where created manually. I got the following error message: OperationalError: (1054, "Unknown column 'supervisor_project.id' in 'field list'"). I'm still a bit confused on when to use unique_together with through. Do you see any errors in the model below? The table supervisor_project has no id field and its PK is composed actually of two FK's, i.e. surrogate PK.

class Supervisor(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True, help_text="Name, e.g. John Smith")

    class Meta:
        managed = False
        db_table = 'supervisor'

    def __unicode__(self):
        return self.name

class Project(models.Model):
    title = models.CharField(max_length=45, blank=True, null=True)
    supervisors = models.ManyToManyField(Supervisor, through='SupervisorProject', through_fields=('project', 'supervisor'))

class SupervisorProject(models.Model):
    supervisor = models.ForeignKey('Supervisor', on_delete=models.CASCADE)
    project = models.ForeignKey('Project', on_delete=models.CASCADE)

    class Meta:
        managed = False
        db_table = 'supervisor_project'
        unique_together = (('supervisor', 'project'),)
Community
  • 1
  • 1
Tin
  • 1,006
  • 1
  • 15
  • 27

1 Answers1

1

Django requires each model to have exactly one primary key field. It doesn't support multiple-column primary keys yet.

Since you haven't explicitly defined a primary key on the SupervisorProject model, Django assumes that there is an automatic primary key field id. When it includes the id field in a query, you get the error because it doesn't exist.

If possible, I would add an auto-incrementing id column to each intermediate table. There isn't a way to get Django to add the column to the tables automatically. You have set managed=False, so Django expects you to manage the database table.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • thank you @Alasdair! How would you proceed in this case. Would you add manually an `id` field to each intermediate table directly in the database? or it's possible for django to create automatically an `id` to each table (defined in the `model.py`)? – Tin Mar 07 '16 at 12:07
  • Thank you @Alasdair! The admin is now working after the correction, i.e. adding the id manually to the DB model. – Tin Mar 07 '16 at 12:54