﻿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
11702	ForeignKey validation should check that to_field is unique	physicsnick	Marcos Moyano	"Currently, ForeignKey validation does not check that to_field is unique. Here is an example:

{{{
class Author(models.Model): 
    code = models.CharField(max_length=10, db_index=True) 
    first_name = models.CharField(max_length=30) 
    last_name = models.CharField(max_length=40) 
class Book(models.Model): 
    title = models.CharField(max_length=100) 
    author = models.ForeignKey(Author, to_field='code')
}}}

Django happily accepts these models. For PostgresSQL and Oracle, foreign keys must be unique, but MySQL and SQLite make no such requirement. MySQL requires only that the column be indexed, and SQLite has no requirements (it does not enforce foreign key constraints).

Django requires uniqueness so it should be enforcing this on its own. The documentation of to_field should also specify that it should be unique.[[BR]][[BR]]

Here is the relevant MySQL documentation:

http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
>> ...MySQL and InnoDB require that the referenced columns be indexed for performance. However, the system does not enforce a requirement that the referenced columns be UNIQUE or be declared NOT NULL.
[[BR]]

Here is some extended discussion:[[BR]]
http://groups.google.com/group/django-users/browse_thread/thread/fcd3915a19ae333e

"	Uncategorized	closed	Database layer (models, ORM)	1.1	Normal	fixed	pycamp2010		Accepted	1	0	0	1	0	0
