#13574: ManyToManyFields using through won't respect to_field parameter in
ForeignKey fields
------------------------------------------+---------------------------------
Reporter: aitorciki | Owner: nobody
Status: new | Milestone:
Component: Database layer (models, ORM) | Version: 1.2
Keywords: | Stage: Unreviewed
Has_patch: 1 |
------------------------------------------+---------------------------------
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.
--
Ticket URL: <http://code.djangoproject.com/ticket/13574>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.