Django Filtering - Field 'testcaseidstring' expected a number but got 'tc123'

Viewed 52

I am trying to apply a filter on a Django model based on a column name

That column is a Foreign Key

Code -

Inside models.py -

class History(models.Model):
    testcaseidstring = models.ForeignKey('Testcaseidstructure', models.DO_NOTHING, db_column='testCaseIdString')  

Inside views.py -

sessid_qs=History.objects.using("otherdb").filter(testcaseidstring="tc123")

This gives me the following ERROR - Field 'testcaseidstring' expected a number but got 'tc123'

How am I supposed to filter on this column?

Testcaseidstructure module:

class Testcaseidstructure(models.Model):
    testcaseidstring = models.TextField(db_column='testCaseIdString')
    class Meta:
        managed = False
        db_table = 'testCaseIdStructure'

Any help would be highly appreciable

Thanks!!

2 Answers

I gues if you want filter by column name you should use testcaseidstring__name in filter, or whatever your name field called in Testcaseidstructure model.

ForeignKey is a number, unless you defined a custom primary key in your model. It's the primary key of the Testcaseidstructure model, so despite the fact that you call it testcaseidstring, it is probably not a string, so rename it testcase. If you want to filter by the string, then you can do something like this:

class History(models.Model):
    testcase = models.ForeignKey('Testcaseidstructure', models.DO_NOTHING, db_column='testCaseIdString')

Then

sessid_qs=History.objects.using("otherdb").filter(testcase__testcaseidstring="tc123")

As suggested by weAreStarDust. Make sure there are two underscores here, testcase__testcaseidstring='tc123'

Related