﻿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
21145	pk_trace fails with ValueError in case when one of the three interrelated models has different primary key type than the others	thepapermen	nobody	"In a project in which all of the models have UUIDs as the primary key, including the custom user model, this bug renders `django.contrib.auth` permission checking unusable (because the Group and Permission models have integer primary keys, but the user has UUID one).

`Permission.objects.filter(**{user_groups_query: user_obj})` in `django.contrib.auth.backends.py` fails.

This bug also renders `django guardian` 3-rd party app unusable. 

The root of the issue is that `pk_trace` incorrectly retrieves the primary key type from intermediary model instead of the last model in the chain.

See line 212:
https://github.com/django/django/blob/d04e8f8c7869b79a6f848a94bd51ce71223c2df2/django/db/models/fields/related.py

Run `check()` below to reproduce:

{{{
from django.db import models
import string
import random


class ModelA(models.Model):
    pass


class ModelB(models.Model):
    modela = models.ManyToManyField(ModelA, blank=True, null=True, )


class ModelC(models.Model):
    id = models.CharField(primary_key=True, max_length=1)  # Or any non-integer PK field
    modelb = models.ManyToManyField(ModelB, blank=True, null=True, )


def check():
    """"""
    This function will fail with ValueError: invalid literal for int() with base 10: 'y'
    which, in turn, points us to the fact that pk_trace for pk of ModelC tries to operate
    with field type of ModelB instead.

    See line 212:
    https://github.com/django/django/blob/d04e8f8c7869b79a6f848a94bd51ce71223c2df2/django/db/models/fields/related.py
    """"""
    a = ModelA.objects.create()

    b = ModelB.objects.create()
    b.modela.add(a)

    c = ModelC.objects.create(id=random.choice(string.ascii_letters))
    c.modelb.add(b)

    return ModelA.objects.filter(modelb__modelc=c)  # Will fail

    # But ModelA.objects.filter(modelb__modelc__pk=c.pk) works like a charm

}}}
"	Uncategorized	closed	Database layer (models, ORM)	1.5	Release blocker	fixed			Unreviewed	0	0	0	0	0	0
