﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
29569	Cast() to AutoField generates invalid SQL	Andrew Standley	Mariusz Felisiak	"Using PostgreSQL 10.1 I encountered a problem trying to use `Cast` with an `AutoField`. Trying to perform a manual join on generic foreign keys:
`Item.objects.filter(pk__in=Activity.objects.filter(content_type=item_ct).annotate(casted_pk=Cast('object_pk', AutoField())).values('casted_pk'))`
The db connection responds with a ""psycopg2.ProgrammingError: type ""serial"" does not exist"" error.

Upon investigation, it seems that `AutoField.cast_db_type` uses the inherited definition from `Field` and returns `AutoField.db_type`.  However `AutoField.db_type` returns 'serial', which is a ""syntactical sugar"" (not a true type) in Postgresql and only valid for creation.
The issue arises when `AutoField.cast_db_type`  also returns 'serial', which is invalid. 

More confusingly `AutoField.rel_db_type` has already been overridden and correctly returns 'integer'. 

I believe fixing this is as easy as copying the override of `AutoField.rel_db_type` to `AutoField.cast_db_type`.
I'll try to at least get this implemented as a test on my fork, so that it is easy to confirm, but in the mean time the models to reproduce are:

{{{
class Item(models.Model):
    label = models.CharField(max_length=100)
    cost = models.IntegerField()

class Activity(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_pk = models.CharField(max_length=100)
    generic_object = GenericForeignKey(fk_field='object_pk') 
}}}

Reference:
PostgreSQL docs on 'serial' type (https://www.postgresql.org/docs/10/static/datatype-numeric.html#DATATYPE-SERIAL)"	Bug	closed	Database layer (models, ORM)	dev	Normal	fixed	cast	Mariusz Felisiak	Ready for checkin	1	0	0	0	1	0
