I have a Django model like this:
class SomeModel(BaseModel):
description = models.CharField(max_length=100)
case = models.ForeignKey(Case, on_delete=models.CASCADE)
is_hidden = models.BooleanField(default=False)
data = models.JSONField(default=list)
I want to store JSON data in the data
field on the model like this:
[{"year": 1, "amount": 10000}, {"year": 2, "amount": 234}, {"year": 3, "amount": 230000, "description": "to principal"}]
I’ve got it working on the client side by inserting inputs with name
values like data[][year]
inside the form:
<input class="form-text-input" type="number" name="data[][year]" required>
The form is sending to the server and my request.POST
is getting it:
<QueryDict: {'csrfmiddlewaretoken': ['xxx'], 'description': ['affa2324'], 'data[][year]': ['1'], 'data[][amount]': ['2342'], 'data[][description]': ['foo'], 'data[][year]': ['2'], 'data[][amount]': ['2355'], 'data[][description]': ['bar']}>
Where I’m having trouble is getting Django to understand that this form data is an array of dictionary values. So far I’ve been handling it by changing the name values to data_year[]
and handling it like this:
year = request.POST.getlist("data_year[]")
amount = request.POST.getlist("data_amount[]")
description = request.POST.getlist("data_description[]")
data = json.dumps(
[{"year": y, "amount": a, "description": d} for y, a, d in zip(year, amount, description)]
)
But it doesn’t scale very well for me in that I have to specialize this pattern for every field in my JSON.
Other frameworks I’ve worked with have understood key[][value]
to be an array of dictionaries, am I missing some better way to do this with Django?