0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Django でテーブルを2つ使う

Last updated at Posted at 2019-02-08

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

著者テーブル
http://127.0.0.1:8000/plural_table/author/
author.png

作品テーブル
http://127.0.0.1:8000/plural_table/work/
work.png

著者名付きの作品テーブル
http://127.0.0.1:8000/plural_table/
plural.png

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

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

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

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

$ 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. アプリの作成
python manage.py startapp plural_table
  1. モデルの作成
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 '<Author:id =' + str(self.id) + ',' + self.name_jp + '(' + str(self.name_en) + ')>'
 
 
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 '<Work:id=' + str(self.id) + ', ' + self.title_jp + '(' + str(self.title_en) + ')>'
 
    class Meta:
        ordering = ('id_work',)
  1. forms.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']
#
  1. views.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)
#
# ------------------------------------------------------------------
  1. urls.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'),
]
  1. admin.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)
  1. static ファイル
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;
}


/* -------------------------------------------------------------- */
  1. templates
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>
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>
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>
  1. マイグレーション
python manage.py makemigrations
python manage.py migrate
  1. プロジェクトの settings.py と urls.py を編集

  2. 開発サーバーの起動

python manage.py runserver
  1. データの入れ込み
     http://http://127.0.0.1:8000/admin/
    で入れるか、SQL で入れます。

完成したコードはこちらにあります。
ekzemplaro
/
django_plural_table

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?