Domanda

I'm having difficulty understanding why one of my queries is failing.

I'm using pyodbc to connect to a SQL Server database on a Django application. All my other queries are working fine, except for one. Here's the relevant info:

Model

class ReportTemplate(models.Model):
    name = models.TextField(db_column='Name', blank=True)
    template = models.TextField(db_column='Template', blank=True)

    class Meta:
        db_table = 'ReportTemplateTbl'

Function

I used 'Abstract' in the example below because it is a known value.

get_initial(self):
    my_template = ReportTemplate.objects.get(name='Abstract')
    return {'abstract': my_template.template}

Error

When the application runs through this function, it returns the following error:

('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'id'. (207) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")

The variable info seems to indicate pyodb is attempting to search

u'SELECT [ReportTemplateTbl].[id], [ReportTemplateTbl].[Name], [ReportTemplateTbl].[Template] FROM [ReportTemplateTbl] WHERE [ReportTemplateTbl].[Name] = ? '

I'd really like to understand what I'm doing wrong here and am trying to avoid making a manual query. Thanks in advance!

È stato utile?

Soluzione

According to django docs, the id column is created automatically. This behavior can be overridden by specifying another attribute as the primary key in the Model subclass:

class ReportTemplate(models.Model):
    name = models.TextField(db_column='Name', blank=True, primary_key=True)
    template = models.TextField(db_column='Template', blank=True)

    class Meta:
        db_table = 'ReportTemplateTbl'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top