| 55 | # A set of models to test m2m relations using non-primary keys as foreign keys. |
| 56 | class Author(models.Model): |
| 57 | name = models.CharField(max_length=50, unique=True) |
| 58 | |
| 59 | def __unicode__(self): |
| 60 | return u'%s' % self.name |
| 61 | |
| 62 | class Book(models.Model): |
| 63 | title = models.CharField(max_length=50, unique=True) |
| 64 | authors = models.ManyToManyField(Author, through='BookToAuthor') |
| 65 | |
| 66 | def __unicode__(self): |
| 67 | return u'%s' % self.title |
| 68 | |
| 69 | class BookToAuthor(models.Model): |
| 70 | author = models.ForeignKey(Author, db_column='author_name', to_field='name') |
| 71 | book = models.ForeignKey(Book, db_column='book_title', to_field='title') |
| 72 | |
| 73 | def __unicode__(self): |
| 74 | return u'%s wrote %s' % (self.author, self.book) |
| 229 | |
| 230 | ## Regression test for #13574 |
| 231 | Check that m2m relations through an existing model where the foreign keys |
| 232 | are using to_field generate correct sql. |
| 233 | |
| 234 | >>> orwell = Author.objects.create(name='George Orwell') |
| 235 | >>> nnf = Book.objects.create(title='1984') |
| 236 | >>> nnf_to_orwell = BookToAuthor.objects.create(author=orwell, book=nnf) |
| 237 | >>> orwell.book_set.all() |
| 238 | [<Book: 1984>] |
| 239 | >>> nnf.authors.all() |
| 240 | [<Author: George Orwell>] |
| 241 | |