0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

django で DB にレコードを登録

Posted at

django で DB にレコードを登録する方法のメモ。

やりたいこと

  • models.py にモデルを定義
  • コマンドでDBにレコードを登録
  • コマンドでDBからレコードを取得

モデルの定義

まず、test1 アプリケーションを作成する。

python manage.py startapp test1

test1/models.py に以下の Item と AttrValue を定義する。
Item の1つのレコードに対して、AttrValue の複数のレコードが紐づく。

test1/models.py
from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=32)

    def __str__(self):
        return self.name


class AttrValue(models.Model):
    item_id = models.ForeignKey(Item, on_delete=models.CASCADE)
    attr = models.CharField(max_length=32)
    value = models.CharField(max_length=32)

    def __str__(self):
        return f'{self.item_id}: ({self.attr}, {self.value})'

レコード登録・検索コマンドの作成

ディレクトリ・ファイル作成

mkdir -p test1/management/commands

cd test1/management
touch __init__.py

cd commands
touch __init__.py

test1 のファイル構成

.
├── __init__.py
├── management
│   ├── __init__.py
│   └── commands
│       ├── create_records.py
│       └── select_records.py
├── models.py
├── tests.py
└── views.py

レコード登録

Xxx.objects.create() でレコードを登録することができます。

test1/management/commands/create_records.py
from django.core.management.base import BaseCommand
from test1.models import Item, AttrValue

class Command(BaseCommand):
    help = 'create records of item, attr_value'

    def handle(self, *args, **options):
        # item1
        item1 = Item.objects.create(name='item_01')
        attr_val1_1 = AttrValue.objects.create(item_id=item1, attr='length', value='10')
        attr_val1_2 = AttrValue.objects.create(item_id=item1, attr='weight', value='20')

        # item2
        item2 = Item.objects.create(name='item_02')
        attr_val2_1 = AttrValue.objects.create(item_id=item2, attr='length', value='15')
        attr_val2_2 = AttrValue.objects.create(item_id=item2, attr='weight', value='25')
  • コマンド実行
python manage.py create_records

レコード検索

Xxx.objects.all() で全レコードを検索することができます。

test1/management/commands/select_records.py
from django.core.management.base import BaseCommand
from test1.models import Item, AttrValue


class Command(BaseCommand):
    help = 'create records of item, attr_value'


    def handle(self, *args, **options):
        items = Item.objects.all()
        print(items)

        attr_values = AttrValue.objects.all()
        print(attr_values)

        items_with_attrs = AttrValue.objects.select_related('item_id').all()
        print(items_with_attrs)
  • コマンド実行
python manage.py select_records
  • 実行結果
    ※わかりやすくするために改行を入れています
<QuerySet [
  <Item: item_01>,
  <Item: item_02>
]>

<QuerySet [
  <AttrValue: item_01: (length, 10)>,
  <AttrValue: item_01: (weight, 20)>,
  <AttrValue: item_02: (length, 15)>,
  <AttrValue: item_02: (weight, 25)>
]>

<QuerySet [
  <AttrValue: item_01: (length, 10)>,
  <AttrValue: item_01: (weight, 20)>,
  <AttrValue: item_02: (length, 15)>,
  <AttrValue: item_02: (weight, 25)>
]>
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?