2

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.

karuoro
  • 541
  • 4
  • 12
  • 1
    Sounds like you need a separate Place model connected via a ForeignKey. – Daniel Roseman Sep 18 '19 at 10:00
  • 1
    Is that seeding fixture a fixed constraint? Because it may need to change in order to solve your problem. – Daniel Holmes Sep 18 '19 at 10:50
  • @DanielRoseman I would work. However, I meant to create a DRY dataset that I can reuse in my later projects. I think I have found a solution that I am posting in the next few minutes. – karuoro Sep 18 '19 at 11:53
  • @DanielHolmes True. I have amended the fixture to fit a Model that works.. I am posting it in a few... Thanks guys – karuoro Sep 18 '19 at 11:54

1 Answers1

1

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!

karuoro
  • 541
  • 4
  • 12