How to use a python list to input data in a Django db? -
say have django model field.
class category(models.model): cat_name = models.charfield(max_length = 200)
and have python script list.py.
def getlist(): name_list = ['a','b','c'] return name_list
how can call getlist create 3 entries: a,b,c 3 separate category entries in django? put them in same dir , import getlist 1 of files in sites dir , run it? or run in terminal?
thanks.
you can either. if you're looking re-usable, should consider creating "initial_data.json" fixture load each time run syncdb
. if you're looking run once or ad-hoc, can this, assuming lives in same directory:
from .list import get_list class category(models.model): cat_name = models.charfield(max_length=200) def __unicode__(self): return self.cat_name @classmethod def create_from_list(cls): values_list = get_list() value in values_list: cls.objects.create(cat_name=value)
then in view, or wherever, can execute classmethod:
# views.py .models import category def my_view(request): category.create_from_list() ...
see: https://docs.djangoproject.com/en/1.6/howto/initial-data/ more information fixtures.
Comments
Post a Comment