DEV Community

Discussion on: BUILD THE REST API USING PYTHON DJANGO - PART 4 🐍

Collapse
aminmansuri profile image
hidden_dude

How do you deal with abstraction when the actions you do on your web page affect many entities?

If your API entities are the same as your DB entities, don't you run the risk of having transactional problems and N+1 problems?

Collapse
codespresso profile image
Codespresso Author

Thank you for commenting. There are certainly a couple of ways to do it, and probably some that I am not aware of (In the software development, we are all in the learning process - foreeveer 😂) - On top of my mind is select_related or prefetch_related, but, essentially the goal is for beginners to get a grasp of building an API with Django. This is a simple, "school" example, where I want to get beginners interested in the matter and to get them just start. And of course, in some future articles, we may discuss N+1, 2N+1....problems. Thank you, again. 😊

Collapse
aminmansuri profile image
hidden_dude

I think you are referring to the server side.
I'm referring to the client side.

If you model your API in a normalized way. How do you generally approach a situation where the UI needs to affect several entities at once? Do you have denormalized abstractions in your API?

Thread Thread
codespresso profile image
Codespresso Author

Well, let's say we have multiple entities, each of which can be standalone entities (no foreign keys) but are referenced in some pivot tables for example. And if I had a situation where the FE sends me a request with all necessary data to create and populate multiple entities, if validation passes, we could first create entities that are not dependable, and after that, we can create all other dependencies. If for some reason it breaks, we can always roll back what we previously created. It is a bit more complex than this, but I would really like to know how do you handle N+1 problems?

Thread Thread
aminmansuri profile image
hidden_dude • Edited on

What I do is I have denormalized abstractions at the REST/Json level.

I model the API based on how the webpages/users want to use them rather than on DB normalization concepts. So that I minimize roundtrips.

Then the backend takes care of parsing the JSON and pumping it all into the correct tables.

This way the client does everything in a single transaction by sending all the form data in one single JSON (no matter how many entities may be affected).