Skip to content
Advertisement

Is it better to use JsonField or multiple model fields for a Django Model?

For example,

class TestModel(models.Model):
    title = models.CharField(max_length = 200)
    descriptions = models.JsonField()

Or

class TestModel(models.Model):
    title = models.CharField(max_length = 200)
    description_1 = models.TextField()
    description_2 = models.TextField()
    description_3 = models.TextField()
    description_4 = models.TextField()
    description_5 = models.TextField()

Assume that I have a limited (max 5) number of descriptions. Which approach is better and would be considered as good practice?

Advertisement

Answer

I am generally in favour of multiple models rather than using JSON, though there is still a time and a place for the JSON field. You have a number of description fields, you can do something like this:

class TestModel(models.Model):
    title = models.CharField(max_length = 200)

class TestModelDescription(models.Model):
    test_model = models.ForeignKey(TestModel, ...
    description = models.CharField(... 

You can then have any number of descriptions and access them like this:

test_model.testmodeldescription_set.all()
10 People found this is helpful
Advertisement