Should I use Django manager for custom model serialization?

I have a markdown data that maps to one of my django model, called Header.

A Manager is a Django class that provides the interface between database query operations and a Django model.

After reading the documentation of manager, I created a following function.

from utils.markdown import  serialize    # I created markdown serializer
class HeaderManager(models.Manager):
  def parse_markdown(self, doc_path):
    headers = []
    for header in serialize(doc_path, "json")["headers"]:
        header.append(self.model(directory=directory, file_name=file_name))
    return header

class Header(models.Model):
  name = models.CharField(max_length=255, null=False)
  level = models.IntegerField(default=-1)
  objects = HeaderManager()

then I call

headers = Header.objects.parse_markdown("markdown_path")
# save all

Is this the right way of using a manager? How about the other way around?

I couldn’t find any documentation or examples that custom serializes (non-JSON) from/to Django models.

<opinion> I probably wouldn’t use a manager to perform any function not related to a query - but that’s just me. YMMV. In this specific case, I’d be more inclined to make this a general utility function capable of being used with multiple models.</opinion>

As far as using non-JSON serializers, the and management commands are capable of importing and exporting data in multiple formats - it uses the built-in serializers for that. You can look at them to see how they work.

1 Like