Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create objects in Django on server startup?

Tags:

python

django

Essentially, I am creating an application where users can have multiple skills. So I have it setup like this:

class Skill(models.Model):
  name = models.CharField(max_length=30)

class Listing(models.Model):
  ...(other stuff for the model here)
  skill = models.ManyToManyField(Skill,)

And then I'm going to create a form that looks something like this:

class ListingForm(ModelForm):
  skill = forms.ModelMultipleChoiceField(queryset=Skill.objects.all())
  class Meta:
    model = Listing

The end result being that I want each skill to show up as a checkbox in the form. So there might be 30 skills to choose from, and then the user could just check any of them that they were proficient in. The problem I am facing is that I somehow have to create those 30 skill objects initially. I know how to create objects, but I don't know where to put the code so that the ~30 skills only get created the first time the server starts. Where should I create the initial skill objects? Is there a better way to do this?

like image 905
reparadocs Avatar asked Oct 16 '25 03:10

reparadocs


1 Answers

You can create a fixtures.json file and use loaddata:

fixtures.json

[
    {
        "pk": 1,
        "model": "appname.skill",
        "fields": {
            "name": "skill name",
        }
    }
}

cmd line:

python manage.py loaddata path/to/fixtures.json

Here are some docs for it: Providing initial data

like image 137
laidibug Avatar answered Oct 17 '25 15:10

laidibug