0

I'm trying to set up a web-app that modify an existing MySQL database using Dajngo, the model for my table below was generated via Django inspectdb:

class BaseCase(models.Model):
    base_case_name = models.TextField(blank=True, null=True)
    version = models.TextField(blank=True, null=True)
    default = models.TextField(blank=True, null=True)  # This field type is a guess.
    class Meta:
        managed = False
        db_table = 'base_case'

and here is an SQL of that base_case table in the database :

CREATE TABLE `base_case` (
  `base_case_name` tinytext,
  `version` tinytext,
  `default` bit(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

the problem is when I try to get the objects via Django ORM I keep getting this error

django.db.utils.OperationalError: (1054, "Unknown column 'base_case.id' in 'field list'")
Mehdi Selbi
  • 147
  • 2
  • 11

3 Answers3

1

I solved the problem by defining a primary key in the BaseCase Table, Django try to match the primary key column to its own generated id (base_case.id) in the field list.

Mehdi Selbi
  • 147
  • 2
  • 11
  • I looked for so long, so long. I had this happen when I was trying to pull an entire table into my views page without specifying a column name. KUDOS to you! – Josh Jul 09 '21 at 03:52
0
$ python manage.py makemigrations

$ python manage.py migrate

run following command in order for changes to be applied to the database.

Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
0
class Images(models.Model):
    name = models.CharField(max_length=100)
    id = models.CharField(max_length=100, primary_key=True)
    image = models.FileField()

def __str__(self):
    return self.name

Set primary_key=True which field you want to set as the primary key.

A.Zahid
  • 1
  • 1
  • 1
  • If you can, it's better if you create the example using OP's base model in order to prevent confusion. Django models already have an id-field by default that's set as the primary key – LoKat Dec 10 '20 at 09:18
  • Actually, it depends on which field he wants to set the primary key to. I gave the example of setting the primary key. – A.Zahid Dec 11 '20 at 09:08
  • That's correct, if you want to use a different field as the primary key you have to specify that yourself. However by default any django Model created has a primary key set by default, which is accessible via `id` on the model. However if you are trying to fetch a model using `Model.objects.filter` you should use the `pk` value: `Model.objects.filter(pk=id_of_obj)` – LoKat Dec 11 '20 at 12:56