﻿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
13574	ManyToManyFields using through won't respect to_field parameter in ForeignKey fields	aitorciki	nobody	"When a ManyToManyField is set to use an existing model with ''through'', Django will fail to generate the correct SQL if a ForeignKey in this model is using ''to_field'' to relate to a field other than the primary key of the target table. That happens because m2m handling code is always assuming that the relation if with the target table primary key.

For models like the following:

{{{
class Author(models.Model):
    name = models.CharField(max_length=50, unique=True)

class Book(models.Model):
    title = models.CharField(max_length=50, unique=True)
    authors = models.ManyToManyField(Author, through='BookToAuthor')

class BookToAuthor(models.Model):
    author = models.ForeignKey(Author, db_column='author_name', to_field='name')
    book = models.ForeignKey(Book, db_column='book_title', to_field='title')
}}}

The generated SQL for an book object (id = 1) access to authors attribute is

{{{
SELECT `author`.`id`, `author`.`name` FROM `author` INNER JOIN `booktoauthor` ON (`author`.`id` = `booktoauthor`.`author_name`) WHERE `booktoauthor`.`book_title` = 1
}}}

while the expected one is

{{{
SELECT `author`.`id`, `author`.`name` FROM `author` INNER JOIN `booktoauthor` ON (`author`.`name` = `booktoauthor`.`author_name`) INNER JOIN `book` ON (`booktoauthor`.`book_title` = `book`.`title`) WHERE `book`.`id` = 1
}}}

I attach a patch that uses the relation field_name attribute instead of assuming that the primary key is to be used."		closed	Database layer (models, ORM)	1.2		duplicate			Unreviewed	1	0	0	0	0	0
