Creating custom model fields

Django comes with a complete collection of model fields that you can use to build your models. However, you can also create your own model fields to store custom data or alter the behavior of existing fields.

We need a field that allows us to define an order for objects. An easy way to specify an order for objects using existing Django fields is by adding a PositiveIntegerField to your models. Using integers, we can easily specify the order of objects. We can create a custom order field that inherits from PositiveIntegerField and provides additional behavior.

There are two relevant functionalities that we will build into our order field:

  • Automatically assign an order value when no specific order is provided

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.