You may have a similar logic in multiple areas of the site to deal with inserting data. You can create a manager function that accepts your data as a parameter and centralizes your insertion logic.
- [Instructor] Here's a situation you may have bumped into.…We'll use our song model as a basis.…You add a new song,…and you want to add the album and artist…for the song at the exact same time.…We can use a manager to do this for us.…You're gonna be surprised…when you see how simple this code is.…You see here that I've created a new model manager…called NewSongManager.…It get all the behavior we just added to the SongManager,…and it adds a new method called new_song.…Note that it takes a song_title,…artist, album, and release_date.…
We use the get_or_create method for the artist and the album…to either look up the PK,…or, if that record doesn't exist, to create a new one.…Then we create a new song and save it.…We then return the song.…One of the best features here is that the code…to create records is now no longer in a view.…If you have several ways…in which new songs may be added to the system,…you never have to repeat your code.…You can even add more sophisticated functionality…and business logic here, which is pretty typical.…
Django is one of the world's leading web development platforms. This Python web framework makes your app building experience smoother, faster, and easier. It is a key feature behind the success of many start-ups across the world, including Instagram and Nextdoor. This course introduces next-level advanced concepts to help you build your own professional-grade Django applications.
Author Kevin Veroneau starts off by explaining how class-based views—a powerful, but often poorly understood feature—work in Django. Then learn how to create custom middleware to help organize frequently used code. Have you ever wanted to build a complete RESTful API? Find out how to do just that, starting with a basic read-only API and then adding key-based authentication to allow the full range of CRUD functionality. Plus, discover how to use model managers and the Q method to make it easier to get the data we need to our views and clients.
For the finishing touches, dive into the details of caching to improve application performance, and then add custom management commands to help automate routine tasks.
- Extending class-based views
- Creating custom class-based views
- Managing your database with middleware
- Creating template filters and tags
- Building a RESTful API
- Modeling advanced database relationships and queries
- Using a model manager for your application