Opened 17 months ago

Last modified 17 months ago

#21508 new Bug

ForeignKey cast to int despite being varchar

Reported by: fiomtec@… Owned by: nobody
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi!

I have a couple of models connected to a read-only sqlserver DB, like this (trimmed to the important details):

class Cliente(models.Model):
    codigo = models.CharField(max_length=8, primary_key=True)
    nif = models.CharField(max_length=15)
    nombre = models.CharField(max_length=100, db_column='nombre_apellidos')


class Confirmacion(models.Model):
    cliente = models.ForeignKey(Cliente, db_column='entidad_propietaria', max_length=8)
    [...]other fields[...]

When I try to find some Confirmacion objects filtering by nif like this:

Confirmacion.objects.filter(cliente__nif=nif).all()

it will correctly find some results, but blow up when I try to access them. e.g., this is a dict from one Confirmacion result:

{'cliente_id': 7502, '_state': <django.db.models.base.ModelState object at 0x000000000433C940>, [...] other fields [...]}

the problem is that the correct cliente_id is not 7502, but '007502', and when I try to access that confirmacion.cliente, I get a "Cliente matching query does not exist" exception.

I also tried using to_field="codigo", same result.

Am I doing something wrong?. Shouldn't the id be a string since the pk is defined as a charfield?.

Thanks.

Change History (3)

comment:1 Changed 17 months ago by MarkusH

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

Looks to me like it is the same underlying problem as shown in #14518 or at least related.

comment:2 Changed 17 months ago by fiomtec@…

Ok, I've been doing a bit more testing. It seems that it doesn't have to do with the column being a ForeignKey, but with the db column being a foreign key. I've redefined my model like this:

class Confirmacion(models.Model):
    cliente = models.CharField(db_column='entidad_propietaria', max_length=8)
    fecha_orden = models.CharField(max_length=8)
    [...]other fields[...]

When I query some objects, fecha_orden will always be a string (despite it being a date in the form YYYYMMDD), but cliente will be a string if it's something like 'MADRID', but an integer if it can be converted.

Both columns are defined as varchar(8) not null in the database, the only difference is that entidad_propietaria is a foreign key to another table, and fecha_orden isn't.

comment:3 Changed 17 months ago by aaugustin

  • Triage Stage changed from Unreviewed to Accepted

Accepting on the basis that the examples clearly demonstrate unexpected behavior.

Note: See TracTickets for help on using tickets.
Back to Top