问题描述
我一直在Django中进行开发,想知道是否有一种方法可以将数据种子植入Django中的数据库中。
I'ved been developing in Django and was wondering if there is a way to seed data into the database in Django.
在ruby on rails中,我使用种子.rb,然后在命令行中运行 rake db:seed。
In ruby on rails, I use seed.rb and then run "rake db:seed" in command line.
主要原因是我希望在项目初始化时使用状态,类型等数据作为种子。
Main reason I want to seed some data on statuses, types, etc for the project initialization.
是有类似的东西吗?
推荐答案
类似于Rails,我们还可以选择为数据库设置种子。使用完成。在您的一个应用中,使用以下文件夹结构
Similar to Rails, we also have option to seed the database. It is done using management commands. In one of your apps, use the following folder structure
<project>/<app>/management/commands/seed.py
这使得 python manage.py种子
可用作管理命令。我个人遵循以下结构。
this makes python manage.py seed
available as a management command. I personally follow the following structure.
# <project>/<app>/management/commands/seed.py
from django.core.management.base import BaseCommand
import random
# python manage.py seed --mode=refresh
""" Clear all data and creates addresses """
MODE_REFRESH = 'refresh'
""" Clear all data and do not create any object """
MODE_CLEAR = 'clear'
class Command(BaseCommand):
help = "seed database for testing and development."
def add_arguments(self, parser):
parser.add_argument('--mode', type=str, help="Mode")
def handle(self, *args, **options):
self.stdout.write('seeding data...')
run_seed(self, options['mode'])
self.stdout.write('done.')
def clear_data():
"""Deletes all the table data"""
logger.info("Delete Address instances")
Address.objects.all().delete()
def create_address():
"""Creates an address object combining different elements from the list"""
logger.info("Creating address")
street_flats = ["#221 B", "#101 A", "#550I", "#420G", "#A13"]
street_localities = ["Bakers Street", "Rajori Gardens", "Park Street", "MG Road", "Indiranagar"]
pincodes = ["101234", "101232", "101231", "101236", "101239"]
address = Address(
street_flat=random.choice(street_flats),
street_locality=random.choice(street_localities),
pincode=random.choice(pincodes),
)
address.save()
logger.info("{} address created.".format(address))
return address
def run_seed(self, mode):
""" Seed database based on mode
:param mode: refresh / clear
:return:
"""
# Clear data from tables
clear_data()
if mode == MODE_CLEAR:
return
# Creating 15 addresses
for i in range(15):
create_address()
在上面的结构中,可以添加自定义模式,并进行相应的种子设定。您也可以添加其他管理命令参数(例如number_of_addresses并将其传递给运行种子。命令将为 python manage.py seed --mode = refresh --number_of_addresses = 15
)。
In above structure you could, add custom modes, and seed accordingly. Also you could add additional management command arguments (e.g. number_of_addresses and pass it to run seed. the command would be python manage.py seed --mode=refresh --number_of_addresses=15
).
希望这会有所帮助。干杯!
Hope this helps. Cheers!
这篇关于如何播种Django项目? -将一堆数据插入到项目中进行初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!