Django is the right way to load a large default into a model

I have a field called schema in a django model that usually contains a rather large json string. There is a default value (about 2000 characters) that I would add when creating any new instance.

I find it unclean to dump everything in models.py in a variable. What is the best way to load this default value into my schema (this is TextField )?

Example:

 class LevelSchema(models.Model): user = models.ForeignKey(to=User) active = models.BooleanField(default=False) schema = models.TextField() # Need a default value for this 

I thought about it a bit. If I use a json file to store the default value somewhere, what is the best place to put it? Obviously, it is preferable if it is in the same application in the folder.

+4
source share
2 answers

The text is quite massive. Will cover half of the file since it is formatted json, which I would like to edit in the future. I prefer to load this from a file (e.g. fixtures), just so I would like to know if the method is already present in Django.

In django you have two options:

  • Listen to post_save , and when created true, set the default value for the object by reading the file.

  • Set the default value to the called (function) and in this method read the file (make sure you close it) and return its contents.

You can also embed data in some k / v storage (e.g. redis or memcache) for quick access. It would also be better since you would not constantly open and close files.

Finally, the most restrictive option is to set up a trigger in the database that populates you. You will need to store json in the database somewhere. The added benefit to this approach is that you can write a django interface to update json. The downside is that it will limit your application to the database that you decide to maintain with your trigger.

+1
source

I believe that using a variable is not particularly unclean. But you can β€œabuse” the fact that the default argument, which supports all fields, can be called.

So you could have this β€œcrazy” thing:

 def get_default_json(): json_text = open('mylargevalue.json').read() return json_text 

and then in the field:

 schema = models.TextField(default=get_default_json) 

I have not tried anything like this, but I guess it might work.

+1
source

Source: https://habr.com/ru/post/1442062/


All Articles