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!!
CodePudding user response:
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.
CodePudding user response:
ForeignKey is a number, the pk of the Testcaseidstructure model, so despite the fact that you call it testcaseidstring, it is 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'