1đź‘Ť
You can do either. If you’re looking for something re-usable, you should consider creating an “initial_data.json” fixture that will load each time your run syncdb
. If you’re just looking for something to run once or ad-hoc, then you can do something like this, assuming everything lives in the 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()
for value in values_list:
cls.objects.create(cat_name=value)
Then in a view, or wherever, you can execute the classmethod:
# views.py
from .models import Category
def my_view(request):
Category.create_from_list()
...
See: https://docs.djangoproject.com/en/1.6/howto/initial-data/ for more information about fixtures.
👤Brandon Taylor
0đź‘Ť
You can use bulk_create method https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create
In your case:
Category.objects.bulk_create([Category(cat_name=name) for name in getList()])
👤GreyZmeem
- [Answer]-How to communicate between client device and webserver?
- [Answer]-Success variable message is assigned referenced before assignment
- [Answer]-Django OperationalError: "Error 'repetition-operator operand invalid' from the regexp"
- [Answer]-Determine the class of a foreign key in Django
- [Answer]-How to convert the foreign key id to the value – Django
Source:stackexchange.com