Search code examples
pythondjangodjango-serializerpython-dataclassesdata-class

Django parse data to model without storing


I was wondering if there is a way to parse a json to an object of the model class without having any databse interaction. If we do what I want to do without django I could serialize a Json into an object class, for example with some help of marshmallow_dataclass

@dataclass
class Example:
    id : int
    name : str

If I do it with a django model and serializer I do it with a standard model serializer and a model class:

serializer = ExampleSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()

So now the question is if there is a way to do combine them. Reason for this, I have a shared model across different applications. Now since some are just processing the data, with there is no need to store it, which I currently do but is a performance drawback. At the same time with combining them I want to achieve to not have to maintain a model and a class with the same fields. Therefore how can I use the model class to parse the data to without having to store them in the database?


Solution

  • If I understood the question correctly, you are looking to have combined validation for the pre-defined model classes, without actually using the django provided methods of having to create a model instance. One interesting method of achieving this is by using pydantic-django for this task. You can create a pydantic model_class to parse the data as is required which will ensure all the validations done for you. For instance, if your example model is as below:

    class Example(models.Model):
        f1 = models.CharField(max_length=255)
    

    the related pydantic class for validation can be:

    from pydantic_django import ModelSchema
    class ExampleSchema(ModelSchema):
        class Config:
            model = Example