[Answer]-How to use a python list to input data in a Django db?

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.

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

Leave a comment