Question
In Django, when using data from an API (that doesn’t need to be saved to the database) in a view, is there reason to prefer one of the following:
- Convert API data (json) to a json dictionary and pass to the template
- Convert API data (json) to the appropriate model object from models.py and then pass that to the template
What I’ve Considered So Far
- Performance: I timed both approaches and averaged them over 25 iterations. Converting the API response to a model object was slower by approximately 50ms (0.4117 vs. 0.4583 seconds, +11%). This did not include timing rendering.
- Not saving this data to the database does prevent me from creating many-to-many relationships with the API’s data (must save an object before adding M2M relationships), however, I want the API to act as the store for this data, not my app
- DRY: If I find myself using this API data in multiple views, I may find convenience in putting all my consumption/cleaning/etc. code in the appropriate object
__init__in models.
Thanks very much in advance.
Converting this to a model objects doesn’t require storing it in database.
Also if you are sure you don’t want to store it maybe placing it in models.py and making it Django models is wrong idea. Probably it should be just normal Python classes e.g. in resources.py or something like that, not to mistake it with models. I prefer such way because maybe converting is slower (very tiny) but it allows to add not only custom constructor but others methods and properties as well which is very helpful. It also is just convenient and organizes stuff when you use normal classes and objects.