Django query auto add 'id' during query process then it error


Today, I have problem when query data from defined model, given that my model does not contain any ‘id’ columns

class Omo(models. Model):
    id_date = models.IntegerField()
    date = models.DateField()
    transactionmode = models.CharField(db_column='transactionMode', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True)  # Field name made lowercase.
    omo_rate = models.FloatField(blank=True, null=True)
    acceptedvalue_bil = models.FloatField(db_column='acceptedValue_bil', blank=True, null=True)  # Field name made lowercase.
    term = models.FloatField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'omo_rate'

Then, in

class AccessDatabase(CreateView):
      def form_valid(self, form, **kwargs):
            cleaned_data = form.cleaned_data
            dateRange = cleaned_data['dateRange']
            dataObject = model_class.objects.using("databaseName").filter(date__range=[dateRange[0], dateRange[1]]).all().order_by("-id_date").values()

It returns the error:

django.db.utils.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'id'. (207) (SQLExecDirectW)")

And I try to find the root cause and find out it automatically add the ‘id’ column to the query. See the picture below

How to solve this problem?

Django requires that every model have a primary key. If there isn’t one defined in the model, Django will add it. See Models | Django documentation | Django

1 Like

Thank you so much, master!