Django でテーブルを２つ使う

Django でテーブルを２つ使うサンプルです。
例として日本文学のオーディオブックのテーブルを使います。
著者テーブルと作品テーブルを使って、著者名付きの作品テーブルを作成します。

著者テーブル
http://127.0.0.1:8000/plural_table/author/
![author.png](https://qiita-image-store.s3.amazonaws.com/0/179446/315070ce-174d-1c17-58af-69560b18e70b.png)

作品テーブル
http://127.0.0.1:8000/plural_table/work/
![work.png](https://qiita-image-store.s3.amazonaws.com/0/179446/32a832aa-0047-21c0-92f9-bc7ea921dd67.png)

著者名付きの作品テーブル
http://127.0.0.1:8000/plural_table/
![plural.png](https://qiita-image-store.s3.amazonaws.com/0/179446/1a5b11f5-403b-cb85-1e7b-54ce9aa484df.png)

Django で MariaDB を使う設定が出来ているところから作業を始めます。

```text
MariaDB [(none)]> create database django_plural_table;
MariaDB [(none)]> grant all on django_plural_table.* to django@localhost;
```

plural_table というアプリを作成します。

完成したアプリのツリー構造です。

```text
$ tree plural_table  -I '_*'
plural_table
├── admin.py
├── apps.py
├── forms.py
├── migrations
│   └── 0001_initial.py
├── models.py
├── static
│   └── plural_table
│       └── css
│           └── plural_table.css
├── templates
│   └── plural_table
│       ├── author.html
│       ├── index.html
│       └── work.html
├── tests.py
├── urls.py
└── views.py
```

1) アプリの作成

```bash
python manage.py startapp plural_table
```

2) モデルの作成

```py:models.py
from django.db import models

class Author(models.Model):
    id_author = models.CharField(max_length=10)
    name_jp = models.CharField(max_length=10)
    name_en = models.CharField(max_length=20)
 
    def __str__(self):
        return '&lt;Author:id =' + str(self.id) + ',' + self.name_jp + '(' + str(self.name_en) + ')&gt;'
 
 
class Work(models.Model):
    id_work = models.CharField(max_length=10)
    title_jp = models.CharField(max_length=50)
    title_en = models.CharField(max_length=50)
    id_author = models.CharField(max_length=10)
 
    def __str__(self):
        return '&lt;Work:id=' + str(self.id) + ', ' + self.title_jp + '(' + str(self.title_en) + ')&gt;'
 
    class Meta:
        ordering = ('id_work',)
```

2) forms.py

```py:forms.py
from django import forms
from .models import Author
from .models import Work

class AuthorForm(forms.ModelForm):
	class Meta:
		model = Author
		fields = ['id_author','name_jp','name_en']
#
class WorkForm(forms.ModelForm):
	class Meta:
		model = Work
		fields = ['id_work','title_jp','title_en','id_author']
#
```

3) views.py

```py:views.py
# ------------------------------------------------------------------
#
#	plural_table/views.py
#
#						Feb/08/2019
#
# ------------------------------------------------------------------
import sys

from django.shortcuts import render
from django.shortcuts import redirect

from django.http import HttpResponse
from .models import Author
from .models import Work
from .forms import AuthorForm
from .forms import WorkForm

# ------------------------------------------------------------------
def index(request):
	params = {
			'title': 'Works',
			'message': 'All Works',
			'form': WorkForm(),
			'data': [],
		}

	if(request.method == 'POST'):
		sys.stderr.write("*** views.py *** POST ***\n")
	else:
		sys.stderr.write("*** views.py *** else ***\n")
#
	array_aa = Work.objects.all().order_by('id_author').values()
	array_bb = []
	for unit in array_aa:
		unit_bb = dict(unit)
		id_author = unit['id_author']
		author = Author.objects.get(id_author=id_author)
		print(id_author,author.name_jp,author.name_en)
		unit_bb['name_jp'] = author.name_jp
		unit_bb['name_en'] = author.name_en
		array_bb.append(unit_bb)
#
#	params['data'] = array_bb[:10]
	params['data'] = array_bb
#
	return render(request,'plural_table/index.html',params)
#
# ------------------------------------------------------------------
def author(request):
	params = {
			'title': 'Author',
			'message': 'All Author',
			'form': AuthorForm(),
			'data': [],
		}

	if(request.method == 'POST'):
		sys.stderr.write("*** views.py *** POST ***\n")
	else:
		sys.stderr.write("*** views.py *** else ***\n")
#
	params['data'] = Author.objects.all()
#
	return render(request,'plural_table/author.html',params)
#
# ------------------------------------------------------------------
def work(request):
	params = {
			'title': 'Work',
			'message': 'All Work',
			'form': WorkForm(),
			'data': [],
		}

	if(request.method == 'POST'):
		sys.stderr.write("*** views.py *** POST ***\n")
	else:
		sys.stderr.write("*** views.py *** else ***\n")
#
	params['data'] = Work.objects.all()
#
	return render(request,'plural_table/work.html',params)
#
# ------------------------------------------------------------------
```

4) urls.py

```py:urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('author/', views.author, name='author'),
    path('work/', views.work, name='work'),
]
```

5) admin.py

```py:admin.py
from django.contrib import admin

# Register your models here.
from .models import Author
from .models import Work

admin.site.register(Author)
admin.site.register(Work)
```

6) static ファイル

```css:static/plural_table/css/plural_table.css
/* -------------------------------------------------------------- */
/*

	plural_table.css

						Feb/08/2019

*/
/* -------------------------------------------------------------- */
table {
  margin: 10px;
	font-size: 14pt;
}

table tr th {
	backqround-color: #009;
	color: green;
	padding: 2px 10px;
	border-width: 2px;
	border:1.5px #7e7e7e solid;
}

table tr td {
	backqround-color: #eee;
	color: #666;
	padding: 2px 10px;
	border-width: 2px;
	border:1.5px #7e7e7e solid;
}


/* -------------------------------------------------------------- */
```

7) templates

```html:templates/plural_table/index.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
<link rel="stylesheet"
 href="{% static 'plural_table/css/plural_table.css' %}">
<title>{{ title }}</title>
</head>
<body>
<p>{{message|safe}}</p>
<table>
<tr>
	<th>id_author</th>
	<th>name_jp</th>
	<th>name_en</th>
	<th>id_work</th>
	<th>title_jp</th>
	<th>title_en</th>
</tr>
{% for item in data %}
<tr>
	<td>{{item.id_author}}</td>
	<td>{{item.name_jp}}</td>
	<td>{{item.name_en}}</td>
	<td>{{item.id_work}}</td>
	<td>{{item.title_jp}}</td>
	<td>{{item.title_en}}</td>
</tr>
{% endfor %}
</table>
<a href="./author/">Author</a><p />
<a href="./work/">Work</a><p />
<hr />
Feb/08/2019 PM 17:25<p />
</body>
</html>
```

```html:templates/plural_table/author.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
<link rel="stylesheet"
 href="{% static 'plural_table/css/plural_table.css' %}">
<title>{{ title }}</title>
</head>
<body>
<p>{{message|safe}}</p>
<table>
<tr>
	<th>id_author</th>
	<th>name_jp</th>
	<th>name_en</th>
</tr>
{% for item in data %}
<tr>
	<td>{{item.id_author}}</td>
	<td>{{item.name_jp}}</td>
	<td>{{item.name_en}}</td>
</tr>
{% endfor %}
</table>
<hr />
Feb/08/2019 AM 10:42<p />
</body>
</html>
```

```html:templates/plural_table/work.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
<link rel="stylesheet"
 href="{% static 'plural_table/css/plural_table.css' %}">
<title>{{ title }}</title>
</head>
<body>
<p>{{message|safe}}</p>
<table>
<tr>
	<th>id_work</th>
	<th>title_jp</th>
	<th>title_en</th>
	<th>id_author</th>
</tr>
{% for item in data %}
<tr>
	<td>{{item.id_work}}</td>
	<td>{{item.title_jp}}</td>
	<td>{{item.title_en}}</td>
	<td>{{item.id_author}}</td>
</tr>
{% endfor %}
</table>
<hr />
Feb/08/2019 PM 17:29<p />
</body>
</html>
```

7) マイグレーション

```bash
python manage.py makemigrations
python manage.py migrate
```

8) プロジェクトの settings.py と urls.py を編集

9) 開発サーバーの起動

```bash
python manage.py runserver
```

10) データの入れ込み
　http://http://127.0.0.1:8000/admin/
で入れるか、SQL　で入れます。

完成したコードはこちらにあります。
[ekzemplaro
/
django_plural_table](https://github.com/ekzemplaro/django_plural_table)