'Fixing django inspectdb after importing postgresql sample database

Context: I'm playing around with setting up a DRF project using the postgresql sample database located here: Postresql Sample DB

Problem: The sample database is already set up with intermediate tables film_category and film_actor. When using manage.py to inspectdb it generates these intermediate tables explicitly (FilmCategory and FilmActor) and they serve no purpose in the code as they only contain the ids for the two related fields. If I were to create them using the Django ORM I could just declare:

class Film(models.Model):
    ...
    actors = models.ManyToManyField(Actor, related_name='films')

Django creates these tables "behind the curtain" so they take up no space in my code. I attempted to just set up a ManyToManyField like so:

actors = models.ManyToManyField(Actor, db_table='film_actor', related_name='films')
categories = models.ManyToManyField(Category, db_table='film_category', related_name='films')

When attempting to migrate, however, this fails giving me the following error:

psycopg2.errors.DuplicateTable: relation "film_actor" already exists

I don't think I want to create this ManyToManyField without explicitly telling it which db_table to use because I believe that would generate an entirely new intermediate table and I lose access to all the data already stored in those intermediate tables in the original sample database.

I was able to get it to work without errors and the expected operations function normally by doing:

actors = models.ManyToManyField(Actor, through='FilmActor', related_name='films')

But now I have an explicitly defined FilmActor and FilmCategory model sitting in my models.py that I cannot remove without causing errors:

class FilmActor(models.Model):
    actor = models.ForeignKey(Actor, models.CASCADE)
    film = models.ForeignKey(Film, models.CASCADE)
    last_update = models.DateTimeField()
class FilmCategory(models.Model):
    film = models.ForeignKey(Film, models.CASCADE)
    category = models.ForeignKey(Category, models.CASCADE)
    last_update = models.DateTimeField()

Has any dealt with explicitly defined intermediate tables generated from an existing DB with inspectdb? Is there a way to get rid of those models that were generated while still allowing the normal ManyToMany operations? Technically what I want to do is working, I just feel like having those two intermediate tables explicitly declared as models in my code when they have no additional data (other than "last_update") feels icky.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source