Inner Join ORM Django

Asked

Viewed 354 times

0

I have 2 models:

class MdlCourse(models.Model):
    id = models.BigAutoField(primary_key=True)
    category = models.ForeignKey(MdlCourseCategories, on_delete=models.CASCADE)
    sortorder = models.BigIntegerField()
    fullname = models.CharField(max_length=254)

class MdlCourseCategories(models.Model):
    id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=255)

When I spin it gives the following error:

(1054, "Unknown column 'mdl_course.category_id' in 'field list'")

What I’m doing wrong?

  • You ran the migrate command to synchronize the database ? PS: It is not necessary to create the id field, it is created automagically... :)

1 answer

1


Error corrected. As noted above, Django automatically sets the name of the Foreign Key column. It turns out that the database already exists and I’m making a system from it.

So I can’t follow Django’s convention. For this I had to search a lot and discover that there is a parameter that is passed in the column of the Model Class for it to use the real name of the column.

Below:

class MdlCourse(models.Model):
    id = models.BigAutoField(primary_key=True)
    category = models.ForeignKey(MdlCourseCategories, on_delete=models.CASCADE, db_column = 'category')
    sortorder = models.BigIntegerField()
    fullname = models.CharField(max_length=254)

class MdlCourseCategories(models.Model):
    id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=255)

The name of the parameter is db_column. And the value you give him is the real name of the column.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.