0
votes

The models are created from the following mysql db with "python manage.py inspectdb --database=mydatabasename":

CREATE TABLE `authors` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

CREATE TABLE `books` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titel` varchar(45) DEFAULT NULL,
  `year` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE `authors_books` (
  `author_id` int(11) NOT NULL,
  `book_id` int(11) NOT NULL,
  KEY `fk_authors_books_2_idx` (`book_id`),
  KEY `fk_authors_books_1` (`author_id`),
  CONSTRAINT `fk_authors_books_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_authors_books_2` FOREIGN KEY (`book_id`) REFERENCES `books` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `awards` (
  `author` int(11) NOT NULL,
  `award_name` varchar(45) NOT NULL,
  `year` int(11) DEFAULT NULL,
  PRIMARY KEY (`author`,`award_name`),
  CONSTRAINT `fk_awards_1` FOREIGN KEY (`author`) REFERENCES `authors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The models looks like this:

class Authors(models.Model):
    name = models.CharField(max_length=45, blank=True, null=True)
    birthday = models.DateField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'authors'
        verbose_name_plural = 'Authors'  

    def __unicode__(self):
        return self.name


class AuthorsBooks(models.Model):
    author_id = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author_id', primary_key=True)
    book_id = models.OneToOneField('Books', models.DO_NOTHING, db_column='book_id', primary_key=True)

    class Meta:
        managed = True
        db_table = 'authors_books'
        unique_together = (('author_id', 'book_id'),)
        verbose_name_plural = 'Author Books'         


class Awards(models.Model):
    author = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author', primary_key=True)
    award_name = models.CharField(max_length=45)
    year = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'awards'
        unique_together = (('author', 'award_name'),)
        verbose_name_plural = 'Awards' 


class Books(models.Model):
    titel = models.CharField(max_length=45, blank=True, null=True)
    year = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = True
        db_table = 'books'
        verbose_name_plural = 'Books' 

    def __unicode__(self):
        return '{} - {}'.format(self.titel, self.year)

In the class AuthorsBooks I have changed the two foreign keys to OneToOneFields.

My admin.py looks like this:

from django.contrib import admin
from myapp.models import Authors
...
class AwardsInline(admin.TabularInline):
    model = Awards

class AuthorsBooksInline(admin.TabularInline):
    model = AuthorsBooks

class AuthorsAdmin(admin.ModelAdmin):
    list_display = ("name", "birthday" )
    inlines = (AwardsInline, AuthorsBooksInline)

class BooksAdmin(admin.ModelAdmin):
    list_display = ("id", "titel", "year" )

admin.site.register(Authors, AuthorsAdmin)
admin.site.register(Books, BooksAdmin)

When I try to change the author on the django admin page I get the following errors: enter image description here

1
Why did you change them to one-to-ones? By definition, that means you can only have one item on each side of the relationship, which is why it complains about but being unique. - Daniel Roseman
It is a combined primary key but I don't know how to define this in a django model. Django import both keys as author = models.ForeignKey(Authors, models.DO_NOTHING) and book = models.ForeignKey('Books', models.DO_NOTHING) then it adds an id field as primary key which does not exists in database. The best thing that i find was the OneToOneField... Perhaps you have a better solution that works? - Tuksn
what you probably want is m2m table and unique_together across these two columns docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many - yedpodtrzitko
Thank you for the hint, I will try it. - Tuksn

1 Answers

0
votes

The only way I get it to work is not to use “composite” or “compound” primary keys. I've added a column id as primary key to the mysql table awards and authors_books. Then I changed back:

 class AuthorsBooks(models.Model):
    author_id = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author_id', primary_key=True)
    book_id = models.OneToOneField('Books', models.DO_NOTHING, db_column='book_id', primary_key=True)
    ...

To:

class AuthorsBooks(models.Model):
    author_id = models.ForeignKey('Authors', models.DO_NOTHING, db_column='author_id')
    book_id = models.ForeignKey('Books', models.DO_NOTHING, db_column='book_id') 
    ...

and

class Awards(models.Model):
    author = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author', primary_key=True)
    award_name = models.CharField(max_length=45)
    year = models.IntegerField(blank=True, null=True)
    ...

to

class Awards(models.Model):
  author = models.ForeignKey('Authors2', models.DO_NOTHING, db_column='author')
  award_name = models.CharField(max_length=45)
  year = models.IntegerField(blank=True, null=True)
  ...

I found no solution with the ManyToManyField, always the same problem. I think the reason is this:

Currently Django models only support a single column in this set, denying many designs where the natural primary key of a table is multiple columns. Django currently can't work with these schemas; they must instead introduce a redundant single-column key (a “surrogate” key), forcing applications to make arbitrary and otherwise-unnecessary choices about which key to use for the table in any given instance.

https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys