Search code examples
djangodjango-modelsforeign-keysseedingdjango-fixtures

Generating a Django Model that can have multiple values in one field


I am trying to generate a Django model that can handle multiple values in a single field. As such, when the first field is queried through a view, a user should select a value for the second field through a select box.

To give a background of the problem, my seeding fixture looks like this...

[
  {
    "model":"myapp.location",
    "pk":1,
    "fields":{
      "county": "countyname",
      "places":{
        "name": "placename",
        "name": "placename",
        "name": "placename",
        "name": "placename",
        "name": "placename"
      }
    }
}
]

In the above scenario, location is the intended name of my model. Now, through a form, I want a user to be presented with 'countynames'. Upon selecting a countyname, the user should be presented with 'placenames' in the selected county for them to choose.

I have tried the following format for the model...


class Location(models.Model):
    county = models.CharField(max_length=100)
    places = models.CharField(max_length=100, choices=places.name)
    def __str__(self):
        return self.countyname

Now, I know that the error that is thrown, ('places' is not defined), is warranted. I was asking whether there is a way to define it (places), as it is in the fixture, or if anyone has a better implementation for such a model... any alternative way is welcome and appreciated as I can't think of anything at this point.


Solution

  • So, after fiddling with two models and foreign keys as suggested in the comments above, I decided to amend the model, which also led to changing the fixture. I read about ArrayFields in Postgres + Django here. I amended the field 'places' to be an ArrayField as shown:

    from django.contrib.postgres.fields import ArrayField
    
    class Location(models.Model):
        county = models.CharField(max_length=100)
        places = ArrayField(models.CharField(max_length=100), blank=True)
    
        def __str__(self):
            return self.county
    

    Next, it was just a matter of changing the JSON fixture to:

    [
      {
        "model":"myapp.location",
        "pk":1,
        "fields":{
          "county": "countyname",
          "places":["placename","placename","placename","placename"]
        }
      }
    ]
    

    After running python manage.py loaddata fixturename.json , it worked and the DB was seeded!