I have a Django model that looks like this -
class History(models.Model):
testcaseidstring = models.AutoField(primary_key=True) # Field name made lowercase.
I am storing String values in this field in the Database
When I make a query on this field like -
qs=qs.filter(testcaseidstring="tc123")
I get an error saying "Field 'testcaseidstring' expected a number but got 'TC123'"
How can I filter on this AutoField?
Is converting that field to a TextField the only way to go?
Any help would be highly appreciable
Thanks!!
CodePudding user response:
From the Django documentation
AutoField - class AutoField(**options)
An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise. See Automatic primary key fields.
So a AutoField has to be an Integer. But you dont have to use a AutoField as the PrimaryKey. For example you can use a CharField as Primary.
testcaseidstring = models.CharField(max_length=100, primary_key=True)
CodePudding user response:
from docs,
AutoField¶ class AutoField(**options)¶ An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise. See Automatic primary key fields.
Using string for AutoField is bad idea, if you look at source code of AutoField,
class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):
def get_internal_type(self):
return 'AutoField'
def rel_db_type(self, connection):
return IntegerField().db_type(connection=connection)
It is inherited from IntegerField. That why you are getting Field 'testcaseidstring' expected a number but got 'TC123'.
