﻿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
23862	ManyToManyRel.get_related_field() doesn't account for defined through to_field	Simon Charette	Simon Charette	"While investigating edge cases `to_field_allowed` has to cope with I stumbled upon the following unusual scenario:

{{{#!python
class Ingredient(models.Model):
    iname = models.CharField(max_length=20, unique=True)

class Recipe(models.Model):
    rname = models.CharField(max_length=20, unique=True)
    ingredients = models.ManyToManyField(
        Ingredient, through='RecipeIngredient', related_name='recipes'
    )

class RecipeIngredient(models.Model):
    ingredient = models.ForeignKey(Ingredient, to_field='iname')
    recipe = models.ForeignKey(Recipe, to_field='rname')
}}}

Which is not correctly handled by the actual `ManyToManyRel.get_related_field()` implementation that assumes [https://github.com/django/django/blob/4b9eb7602d6d8756933d1a767004155a263cc150/django/db/models/fields/related.py#L1349-L1355 this is always the primary key on the target model].

Since `ManyToManyRel` is an implementation detail the provided test is against `ManyToManyField.get_choices()` method which relies on it. The patch also includes tests for related managers interaction since this reference scenario was not tested in `m2m_through` yet.

The fact that the implementation doesn't actually return the correct field means that we don't have to backport the required `to_field_allowed` adjustments (which I'll submit as another ticket/patch to facilitate backports of #23754 and #23839) since it never worked in previous Django versions."	Bug	closed	Database layer (models, ORM)	dev	Normal	fixed			Ready for checkin	1	0	0	0	0	0
