Quantcast
Channel: dictionaryタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 99

Django の model を dictionary に変換

$
0
0

Django の model を dictionary に変換するサンプルです。

management/commands/show_cities.py
# ------------------------------------------------------------------
#
#   management/commands/show_cities.py
#
#                       Feb/15/2019
#
# ------------------------------------------------------------------
from django.core.management.base import BaseCommand
from city.models import City

# ------------------------------------------------------------------
class Command(BaseCommand):
    help = 'Display cities'

    def handle(self, *args, **kwargs):
        instance = City.objects.all()
        for city in instance:
            str_out = city.key + "\t"
            str_out += city.name + "\t"
            str_out += str(city.population) + "\t"
            str_out += str(city.date_mod) + "\t"
            print(str_out)
#
        print("---")
#
        for unit_aa in instance.values():
            str_out = unit_aa['key'] + "\t"
            str_out += unit_aa['name'] + "\t"
            str_out += str(unit_aa['population']) + "\t"
            str_out += str(unit_aa['date_mod']) + "\t"
            print(str_out)
#
# ------------------------------------------------------------------

モデルは次のように定義されているとします。

city/models.py
from django.db import models

class City(models.Model):
    key = models.CharField(max_length=10)
    name = models.CharField(max_length=20)
    population = models.IntegerField(default=0)
    date_mod = models.DateField()

    def __str__(self):
        return '<City:id=' + str(self.id) + ', ' + \
            self.key + ', ' + self.name + '>'

実行例

$ ./manage.py show_cities
t0901   下野  31879999    2011-05-20  
t0902   小山  81392   2015-04-09  
t0903   足利  68321   2012-08-02  
t0904   佐野  12395   2010-09-15  
t0905   真岡  64327   2009-11-27  
t0906   日光  25184   2008-01-14  
t0907   鹿沼  31265999    2006-06-08  
---
t0901   下野  31879999    2011-05-20  
t0902   小山  81392   2015-04-09  
t0903   足利  68321   2012-08-02  
t0904   佐野  12395   2010-09-15  
t0905   真岡  64327   2009-11-27  
t0906   日光  25184   2008-01-14  
t0907   鹿沼  31265999    2006-06-08

参考情報

Django のカスタムコマンドの作り方


Viewing all articles
Browse latest Browse all 99

Trending Articles