Back to the video

Modernizing CRUD Operations in Django

Transcript

By Hicham Bakri. From DjangoCon Europe 2024. Published July 11, 2024.

Watch the video Markdown version 4,163 words · auto-generated · en

Summary

Hicham Bakri explains how Django Ninja can be extended to reduce repetitive CRUD endpoint code in large Django applications. He presents composable, class-based API views and view sets that generate common create, read, update, and delete operations while allowing schemas, paths, model initialization, and business-specific behavior to be customized or reused across API versions. He also describes a separate testing approach based on isolated scenarios, allowing one endpoint test to cover different users, permissions, objects, requests, and expected responses. The work resulted in packages for reusable Django Ninja CRUD views and Django REST Testing, with future plans including broader request support, asynchronous views, more operations, and possible framework portability.

Transcript

Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.

0:00 Introduction

Thank you. Thank you, thank you. Yeah, so let's start. As you said it's about trying to modernize even more application using Django Ninja. So let's start about how I'm gonna present it. So first we are going to see Django Ninja. If you don't know either yet what are the challenges that I faced with large scale applications then my vision and kind of potential solution spoiler Django and detailed examples also how I tried also to not only improve the developer experience

In order to develop endpoints but also the testing experience. And then finally the future directions, conclusion and maybe final thoughts. So first who am I who am I? So is it working? Yeah. So first yeah, I grew up in Normandy in France, so on the north. And then I moved at Toulouse at the south. for my studies and I stay there in order to work at Pixelia. It's a little startup with a couple of friends where we are developing AI tools for computer vision. And in my free time sort of playing yeah football, music painting and developing of course and used web or mobile applications

1:35 Django Ninja Overview

and recently open source so you see with two packages and for now yeah it's been five years that I've deployed I've been using Junk and Django Ninja for two years. Yeah, so next introduction to Django Ninja. If you didn't see it two years ago, Vitalikus, the creator of Django Ninja made in introduction but it was remotely since because of the pandemic and stuff. So a little summary about it. I was all of you maybe know like it's kind of fast API developer experience where you have easy the serialization using pyden tick schema and an open API documentation like

automatically. It's not a big deal since you can do it with other frameworks too, like Django Respermock. But it's kind of cool to have it. And let's start the fight. No, I mean it's a joke because it really like what I'm trying to say it really depends on you. I mean each one of you c can have some preference It's not like a framework is better than anyone else. Okay? So for example, what do I personally love about Django Ninja? It's the abstraction level, like taking the serialization and deserialization layer just a little bit higher. So you don't have to do it in your G function. So yeah, it's done in a middleware layer. So yeah, I really like it.

3:09 Endpoint Duplication Challenges

You just have to define yeah, just like this. Example I don't know if you can see code really at the backstage. But yeah, just a example so it's visual and yeah, I'm not just talking like that. So yeah, so what are then if the you know the developer experience is quite increased with the Django Ninja. What are the problems that I faced? Okay, just like any frameworks you would be using, you have at a certain moment a lot of models, a lot of repetitions in the services that are using it, updating it, and also at the endpoints. So for the services, service layer it's quite easy. I mean it just function

and you are doing quite everything you want with it. But for endpoints I found it quite difficult. I mean, even though I was refactoring my code all the way I wanted with the services, I had a lot of repetition on the endpoint layer too. So duplicate duplicated logic Okay, sorry. Increases of course the risk of inconsistencies. So my next question was how can I fix all of those problems? How can I minimize as I've written? play code and repetitive endpoints. How can I do it in order to yeah just be less frustrating when you are developing all of the stuff and when I don't know

4:41 Composable API Views

Salespeople are asking you a new vertical in your app application you have to repeat a lot of stuff and how to not just rush quick. So yeah a lot of questions that I try to basically try to respond it. And all of this started one year ago when I was vacationing Palma de Mallorca, so it's kind of fun that it was in Spain and now I'm back here. So yeah. I was trying to think about how could I fix all those problems. So one of those key was okay there's some components some sorry some views that was repeated a lot all over my application. Sometimes it was for example a concrete one

The read operation I had a lot of get functions over an object that was repeated for different schemas. Sometimes you just want a little bit of in information, sometimes more, sometimes only IDs and listing IDs of specific objects. You have a lot of prohibitions and existing solutions like viewsets in Django Rasp Primox, for example, didn't offer the flexibility of defining several crowd actions, for example. And you had with inheritance only one possible impl implementation of each view. So I was thinking about how to how can I treat them as components, like

a notion, a word, What you obviously often see in front-end development, but we are only taking the good side of it, all right, not JavaScript. And the key specifications include yeah, so class-based view components, even though it doesn't exist in Django. ninja. And that's not exactly what I'm trying to do or implement like expose class based views for every people using Django Ninja, but it's just that I need it in order to declare my views as model of as I ever wanted to. And yeah, so easy of creation of course the goal is to ease the way off the way for people to create their own modular views. It depends on your specific

yeah your specific business logic. It's not always about repetitive crowd endpoints everyone ever saw. So first how to create this potential core objects. So As you may know, yeah, the basic way of creating a gate operation, for example in order to read let's say department object, it's really a basic object, right? Just have an ID, an autofill, and a title. You wanna get it with Simple schema, you just get the object. Okay. From this, if you check the code of the get method on the router, you see that it just really about API operation with methods get. Okay. And from it, if you read the code of Django Ninja, you see

See that it's just wrapping up the method add API operation in a decorator. So from it, okay, I could create an object called API view , make the method path, all the attributes in it, and abstract away the view function that I could just return with a key method called as operation, as a dict, and use it when calling router ad API operation with the return. results as a dictionary. So we have a method to a way to define an object, serialize it and use it in order to add the operation. So we just need the router, the object, and we can add

8:30 CRUD View Sets

view. But then how to compose it in what I called API view sets. How to manage them and group them with I don't know, maybe and surely, with I don't know, yeah. similar properties like model of course. So yeah first I had a look at init subclass. It's kind of init for instances but for classes. So as soon as you're inheriting this API view set Well, I can access all the subclass, all the class attributes of it, and especially the instance, the subclasses of API view. So you just have to inner it from API view, put it as a class attribute to API view. set

and then I can just iterate over it to change of course the view function name to because it's gonna be generic of course to the class attribute name so at the same time I'm dodging like the conflict possible with view function Name. I'm then accessing the API view set from each module of views. So you can access similar like same properties on the API view set in the module of views and then call the function the method. add view to that is doing what I just talked about previously, like serializing your API view in as operation and call the router with it. But then it was a little bit too abstract. could not expose this to every one of you, everyone

every users and just say, Okay, let's go, you can create now your own API views. I had to take some really fundamentals that were both repetitive and common to everyone. And thanks there's like some invoice called Create Read Update and Delete the Crud that was first introduced in nineteen eighty three by James Martin. Hope you maybe read the book, but yeah. Though was like I found with those the exact kind of endpoints I needed in order to showcase how to declare your views are modular alike as components. So yeah, it was kind of the introduction of the package. So I could expose it to everyone, make it understanding

understand and see exactly directly how is it how you're gonna how you could have the declarative and iterative syntax to kind of every endpoints. You see easily with CRUD and you can easily think about it for your repetitive and common logic inside your proper business logic. So Yeah, just like that you I have defined like five classical classic views and be able to compose my view set as I ever wanted, even for example use the list views sever several times as Like I said, for example you can list a department with a simple schema and an extended one with related

Objects and a simple one with just the IDs you can do whatever you want but you inde identified correctly that those endpoints were kind of the same and could be possibly refactored at the top level, I mean at the definition. Okay. A little bit too abstract so bit of code. Well it's directly doing what we are writing it, you just see that I've leveraged the inheritance of values in the API view sets. So you just have For example, you s you know that the view set link to department object is going to have views that are going to use the models.

So if I access it and access the default schemas, I could easily Lead create list, create, read, and update, delete, use. So just like that, in several lines of code, you just abstract away kind of the boilerplate code in order to expose a new model that you just integrated in your application. Any a key part is the reuse the same in same views in the same view sets. So for example if you if you have a migration of a schema, for example, the head of the exposition of a new field or rename a field for Certain clients, you could just add a V2 path and just expose the same schema without the need to rewrite another endpoint.

13:00 Customizing CRUD Operations

So yeah. Again, a lot of abstract. talks so we need concrete examples like what does it really look like. But first some vanny Django ninja code. So you see when you are reading writing a classic lead For example, I'm going to do exactly the same for all the five endpoints. You have the basic one, let's say it's your proper business logic endpoint, or right, not a cred endpoint, you have to identify around all the use of it. What's really similar in order to find a perfect interface. Like it's a general problem, okay? You have to define your own function. I could not do that but I

kind of done it for basic thread operations. So yeah, once you found the basic request components, maybe some method around it, pagination class, of course, even though I put a default like Django Ninja has done with limit offset paginations. So Yeah you could easily write some complex endpoints but also really easy to read. For example here I'm easily defining a list employees endpoint. to departments. Yeah, I didn't introduce the Django models, but you can easily know that employee has a foreign key to department object. So yeah from

Direct path where I know the I ID is from the model defined that is in the view set and in the view that yeah the ID is the one from department and then you can easily define your schemas and have your handpoint. So we declarative and kind of really usable but one time again I'm really like defining the tools to define it. You are free to not use the once I've like the crowd views, my implementations of CRUD views, you can extend them really easily The key here is that you just have to define them as class attributes. So if you are creating your own custom view, it's gonna be another class. You don't have to change the API view set, you just have to add it as a class attribute.

And just like that you have your you compose your view set as I said. And yeah, you can do the same for the other one, like create what's changing like init model. Maybe you're asking why, because sometimes you could have like with so with the listing employees, some path parameters like okay if you specifying ID and then something else or even name or even any path parameters you ever wanted, there's gonna be some path par managers and maybe you are going to use it in your in the model. For example, even the request in order to link I don't know if you are storing the created by user yeah and other yeah pre-save and post save

Like I prefer to do it and you maybe should do it here in the endpoint or in the service layer instead of the signals and joking inside the models. But yeah, since it was kind of a little bit opinated to force users to have the full clean method. I've put it in a pre save that you can easily overwrite if you wanna use directly my implementations of yeah my views here create view. And one time again yeah it's It's in the blue one are always written like the request components. But yeah. So once again you can easily define some complex but same view, you just have to define a little bit more parameters. So yeah, as I said in the init

model method, I don't know if re far from the screen you can see the code, but I I'll share the slides right after. The init model you just have to re root the Passparators ID in the department ID in order to, as I said, override the in if model so you have everything you can want to. And we can do the same. Well yeah. I'll skip this part because I think you and understood the idea. You just identify what could be customized in order to be used real largely and minimize the code wherever it's possible. So I've done the same for updates. And then you have it. And yeah, something I just talked about previously

was the possibility of defining just a new schema for the same operation really easily by just specifying the path. Like just path ID V two and you have it. Just link it to the right schemas. And finally, yeah, delete kind of the same. I expose it pre delete and positive operations and a get model that I never overwritten. But I'm just exposing it in order to say that yeah I'm allowing any kind of customization, but you're free to do whatever you ever wanted. And yeah, and maybe not more yeah. And let's get How yeah, some

18:33 Custom API Views

key component in the package is how can I abstract away the link and know which parameters it is of what type. It's really easy when you have the package. Path in the model you can easily extract all the strings from your path, like the path monitor's name, and linked it with your model in order to know exactly which field in it is it. So you have kind of access get fields from the models meta arguments and then you have it. You can dynamically generate sorry at runtime your identity schema And yeah, the key parts, so as I said, you can easily

add your custom views because it's all it is about like creating some component like views for you proper to your business logic, not only Crowd operations. So yeah, I've talked about it about how to do it. Yeah, again a lot of code. I hope really far away from the screen is okay. As I said, you just have to inherit from the API view class. Where you define the interface you want it to so it's really it's proper to your needs. But I've done an example using the self delete operations where you could do it with an update but it's not an update. And sometimes you wanna yeah just define your repetitive operations and you just have to define an inner

view function. And yeah, it's just easy at that and you can reuse it with one line everywhere you want. across several view sets or inside the same one. So you know if you are migrating schemas as I said. So yeah, really easy to define your own one. Just use API view set and your custom view and it's okay. So yeah, now that I have showcased all the features kind of the package, what's coming after, of course a little bit of fix because I have one issue that abstract too much the API view class. I I've made it too opinionated around the CRUD operations. Like I've really made it

20:52 Future Directions

with as inputs only three parameters, the request one, path query body, when you could potentially have file header or cookie. Like it's kind of a lie to say that today we can compose any custom view but it's gonna be real soon like yeah matter of weeks before I got this and yeah, of course implement the most ask feature like showcase how to create some async views to yeah make people happy about it and you know just be on the trend. And then I could maybe think about a V one that way I'm waiting since one year and maybe provide some other common crowd operations, even though it's maybe not the goal of this package

is not to showcase how to do it, but not like use all the tools I will pride in the future. And maybe yeah, extend the vision of the framework. What does that mean is at first I really wanted to make this available as I said it does not depend on the frameworks. So maybe adapt It's easily to Django REST framework or FAST API or anything, you know, just you know to define some compostable approach. But I don't know yet. I just see the V one and then we are going to But yeah, my experience here didn't stop to trying to enhance the developer experience on the specific task of defining endpoints.

22:26 Testing Experience

I also tried to tackle the testing experience. experience was a little bit harder because yeah it was a lot of also repetitive. At first I was really naive because I tried to kind of r repeat the same pattern like having some component like test objects. While it kind of sounded quite right at first, one year after I would never do that again. Why? Because it was just hidden. It was Just yeah, some code was hidden. You were not probably aware of what you were testing all over your applications, you're just using a random test component like object

and it will not take the responsibility of saying to you that okay, you are really testing everything. If you put this in your test, it's okay. I was not really convinced and it was really bringing a lot of more problems there. Solutions. That's what kind of the thing I try to do like link the what? Oh 33 actually. Yeah, but I try to link all the tests together like that. with the names it was kind of working but as I said kind of lack of flexibility and kind of really rigid. So yeah it was not no generalization was possible because I was through constraining

the status code and stuff. Yeah, I just skip it to you because it was really a mess. The important part was is that I s successfully like flattened all the errors I've made and just throw them away. With an object called scenario where I'm just it's really just a black box with inputs, request components and expected statement on the response. For now it's really basic, it's just Straight away the need to do the HTTP call and the use of the client. But yeah I found this interface a way more easy in order to manage all your scaled tests over your big

application. And yeah, I really like the way it goes. J only one test for specific endpoint where we you are testing a lot of scenarios together. And the key here is that you can test it for example with several users with different permissions and on different objects and every scenario completely isol isolated with a database fullback as I've written. And yeah it was so after the separation and the complete rewrite of it and separation of Django Ninja it was just depending on Django. So I was like, okay, maybe it's it does not have a spot like in this package. So I separated it even though it's kind

25:30 Conclusion and Acknowledgments

I say a little bit small but yeah, it's the little brother of Django ninja crit. I've named it Django rest testing and yeah. Take a look. So yeah, that's a conclusion. Yeah it was really time consuming to do all of those the two packages, the maintenance and the think about the features kind of alone so it was really hard and time consuming, even though it's really valuable learning experience. Yeah, I've improved the developer experience for me, so why not for everyone? I hope it's gonna work. So yeah. I just wanna thank all the stage contributions.

And sponsors of the packages. Really great without you it was it would have been a lot of more difficult. Of course, thanks to GitHub, README and JadeBrains for the open source license. Even though GitHub It's kind of natural but we are for kind of not aware of all the advantages of Gifab. And of course thank you Jang Rukan organizers for