Search code examples
djangoforeign-keysdjango-model-field

Django - right way to join not-django tables


I have old cms database, structure isn't perfect and it can't be modified but i need to query using django

TABLE posts (post_id)

TABLE posts_text (post_id, post_text)

TABLE episode (id, season_id, episode_name)

TABLE episode_post_relationship (id, season_id, episode_id, post_id)

Please help me to create django models with right tables relationships. Should i use OneToOneField, ForeignKey, ManyToManyField and etc or pure join?

I'm trying to get Episodes from episode_post_relationship table with posts_text.posts_text and posts.some_other_col but can't specify that episode_post_relationship table should join posts_text on post_id and the same for posts table.


Solution

  • As per documentation, you can connect to legacy Databases as well. For that, you need to connect your current Django project to that DB, for example, create a new project by django-admin.py startproject yourproject, then go to settings and update the DATABASES setup like this:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', 
            'NAME': 'DB_NAME',
            'USER': 'DB_USER',
            'PASSWORD': 'DB_PASSWORD',
            'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
            'PORT': '3306',
        }
    }
    

    And then run python manage.py inspectdb. You can also output it as a model like python manage.py inspectdb > models.py

    Update:

    From what I can see, your DB should be:

    class Post(models.Model):
        post_id = models.AutoField(primary_key=True)
    
        class Meta:
            db_table = 'posts'
    
    class PostText(models.Model):
        post = models.ForeignKey(Post)
        post_text = models.TextField()
    
        class Meta:
            db_table = 'posts_text'
    
    class Season(models.Model):
        # season fields
        class Meta:
           db_table = 'season'
    
    class Episode(models.Model):
        season = models.ForeignKey(Season)
        episode_name = models.CharField(max_length=255)  # depends on your DB
        posts = models.ManyToManyField(Post, through="EpisodePost")
    
        class Meta:
            db_table='episode'
    
    class EpisodePost(models.Model):
        season = models.ForeignKey(Season)
        episode = models.ForeignKey(Episode)
        post = models.ForeignKey(Post)
    
        class Meta:
            db_table='episode_post_relationship'
    

    But, before you do anything with above relations, please make sure to have a backup of your current DB.