0

I am new to Django Json Field. I have been creating models and migrating them for now. Now I am introduced to Jsonfield. What I have heard is, it is the best way to mitigate the migrations issue because of jsonfield. It is because, if we had to add fields or remove fields from the model after populating the fields (if we have used other regular fields like chafield and emailfield) in production, there may arrise migration issue which we can avoid if we use jsonfield becaue we can just pass any json data with any number of fields in the jsonfield. So, is this the best way to avoid migration issue?? I am seeking expert advice here, because there is no one I can ask and that is what I have heard.

It seems like this.

class Example(models.Model): 
    
    data = models.JSONField(null=False, default=dict)

So, instead of creating two models named Contacts and Feedback for saving the data of contact form and feedback form, I can simply use this same example model and validate to accept any data of many such forms existing in the frontend.

Reactoo
  • 916
  • 2
  • 12
  • 40

1 Answers1

2

If you want to use JSON just to avoid migrations, then that's not a good idea.

Basically, there are these two rules for using JSON:

  • If the data doesn't have a strict structure.
  • If you don't need to query (filter, search, order, etc.) the database using the given data.

Consider this example:

class User:
    email = EmailField()
    address = JSONField()

The email is in a separate field because we want to easily query the database to check for duplicate sign-ups.

The address is in a JSONField because we won't need to query the database using address data.

However, some applications may require to query using address, for example, to list all users from a particular city. In that case, using JSON will be a bad choice.

xyres
  • 20,487
  • 3
  • 56
  • 85
  • Hello xyres, thank you for the answer, but I think I have done database query and filtering using. Example.object.filter(...somthing) and it worked. Looking for your view on this though.... – Reactoo Oct 10 '21 at 07:03
  • 1
    @Django-Rocks You can certainly query JSON data, but it will be less efficient than if the keys were in separate columns. If querying is not done very often, perhaps it won't be a problem. – xyres Oct 10 '21 at 07:17