[Django] Carefully explain the escape route if you really want to use the table of another application

Introduction

It took me a while to find out how to use the table of another application, so I will write it as an article.

Solution

There are two main ways to do it.

1. 1. Import and use the model of the table you want to use

This method is explained this time.

2. Integrate apps

Integrate apps that want to share a table as one app. According to Django's basic idea, "Each app shouldn't have a dependency", ** This is a straightforward approach ** </ font>.

Briefly, when there are apps A </ font> and B </ font>, they are defined on the A </ font> app. The fact that B </ font> uses the created table means that B </ font> has A </ font>. This is because it will be the first app to work = ** " B </ font> depends on A </ font>" **.

** However, ** I think there are times when it is not possible to make major modifications to integrate the app into a system that is already running in a production environment. In this article, I will introduce an escape route that can be used in such cases.

  • If it is still under development or if it is not too late to fix it ** Method 2 is highly recommended **.

point

If you use PyCharm or VSCode you will see an error inspection (probably in other IDEs and editors) ** Ignore it **. Python has a rule that ** import source must be in the same hierarchy or lower hierarchy **, but it is a method to somehow import by a rule-breaking method.

Commentary

Actually create an app A </ font> and an app B </ font>, and from B </ font> to A A < Go look at the / font> table.

  • As a premise, it is assumed that Python is already installed. Create a Django app with the following command
> mkdir django-model-test
> cd django-model-test
django-model-test> python -m venv venv
django-model-test> venv\Scripts\activate  #For Windows
django-model-test> source venv/bin/activate  # Mac,For Linux
(venv) django-model-test> pip install django
(venv) django-model-test> mkdir Src
(venv) django-model-test> cd Src
(venv) django-model-test\Src> django-admin startproject config .
(venv) django-model-test\Src> python manage.py runserver

If you access localhost: 8000 and the Django demo screen is displayed, this is OK. image.png

Quit the test server with Ctrl + C and continue. Execute the following command

django-model-test\Src> python manage.py startapp appA
django-model-test\Src> python manage.py startapp appB

Added to INSTALLED_APPS in settings.py

django-model-test\Src\config\settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #Postscript
    'appA.apps.AppaConfig',
    'appB.apps.AppbConfig'
]

Set urls.py

django-model-test\Src\config\urls.py


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('appB/', include('appB.urls', namespace='appB'))
]

django-model-test\Src\appB\urls.py


from django.urls import path
from . import views

app_name = 'appB'
urlpatterns = [
    path('', views.top_page, name='top_page'),
    ]
]

Create index.html (and destination directory)

django-model-test\Src\appB\templates\appB\index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Reference success!
</body>
</html>

Create a test table in models.py of appA

django-model-test\Src\appA\models.py


from django.db import models


class AppATable(models.Model):

    sample = models.TextField()

Execute migrate from the terminal

django-model-test\Src> python manage.py makemigrations
django-model-test\Src> python manage.py migrate

Finally, create the essential Views.py! Probably the third line cannot resolve the reference and an error occurs, but please ignore it.

  • Please be sure to migrate before creating

django-model-test\Src\appB\views.py


from django.shortcuts import render
from django.views.generic import View
from appA.models import AppATable


class TopPageView(View):
    def get(self, request, *args, **kwargs):

        appATable_data = AppATable.objects.all()
        print(appATable_data.values())

        return render(request, 'appB/index.html')


top_page = TopPageView.as_view()

Put the test data in the DB. This time I did it from the IDE, but if you don't have the tools, you can enter it from the Django admin site. image.png

That's all for preparation. Let's start the test server and access [localhost: 8000 / appB]. It is OK if the text "Reference successful!" Is displayed on the browser and the result of the print statement (contents of appATable) is displayed from the terminal. image.png image.png

That is all. Thank you for your hard work: cat2:

Recommended Posts