1

Consider I have a Django model with a custom JSONField as below,

# models.py

class JSONCustomField(models.JSONField):
    ...


class JSONFieldModel(models.Model):
    json_field = JSONCustomField(default=list)

This model is connected via Django Admin

# admin.py

@admin.register(JSONFieldModel)
class JSONFieldModelAdmin(admin.ModelAdmin):
    def expected_json(self: JSONFieldModel):
        return self.json_field

    list_display = ("id", "json_field", expected_json)

This setup resulting an output like the below,

Current Output

Questions

  • Why JSON FIELD and EXPECTED JSON display different results in Django Admin? (It's supposed to be the same, right?)

  • How can I tell Django to parse and display my "list of strings" to "comma separated strings" as EXPECTED JSON represents? That is, how to tell Django to give me result as EXPECTED JSON while adding the custom field to the ModelAdmin as a string ("json_field") in Django Admin

Notes

  • Django version 3.2.X
  • Assume that the json_field will only accept list inputs (Just like an ArrayField)
JPG
  • 82,442
  • 19
  • 127
  • 206
  • do you need to change the data in the database or only in the admin panel? – inquirer Oct 01 '22 at 15:53
  • Both. But, how does that relevant to the OP? @inquirer – JPG Oct 01 '22 at 16:00
  • What is OP? If the data needs to be changed in the database, then they will change in the admin panel. I roughly know how to turn a list into a string separated by commas. If so, let me know. – inquirer Oct 01 '22 at 16:07
  • If you look at the image, I was getting the expected result with a custom setup (`expected_json`/`EXPECTED JSON`) using `expected_json(...)` function. But, Django not giving the same result when I mention the field name (`json_field`/`JSON FIELD`) – JPG Oct 02 '22 at 05:24
  • I'm happy to see the solution that doesn't add custom column methods (just like `expected_json(...)`) to the `ModelAdmin`/`JSONFieldModelAdmin`. – JPG Oct 02 '22 at 05:26

0 Answers0