Home > Mobile >  Django: Are Django models dataclasses?
Django: Are Django models dataclasses?

Time:11-09

Can we say that Django models are considered dataclasses? I don't see @dataclass annotation on them or on their base class model.Models. However, we do treat them like dataclasses because they don't have constructors and we can create new objects by naming their arguments, for example MyDjangoModel(arg1= ..., arg2=...). On the other hand, Django models also don't have init methods (constructors) or inherit from NamedTuple class.

What happens under the hood that I create new Django model objects?

CodePudding user response:

A lot of the magic that happens with models, if not nearly all of it, is from its base meta class.

This can be found in django.db.models.ModelBase specifically in the __new__ function.

Regardless of an __init__ method being defined or not (which actually, it is as per Abdul's comment), doesn't mean it can or should be considered a dataclass.

As described very eloquently in this SO post by someone else;

What are data classes and how are they different from common classes?

Despite django models quite clearly and apparently seeming to have some kind of data stored in them, the models are more like an easy to use (and reuse) set of functions which leverage a database backend, which is where the real state of an object is stored, the model just gives access to it.

It's also worth noting that models don't store data, but simply retrieves it.

Take for example this simple model:

class Person(models.Model):
    name = models.CharField()

And then we did something like this in a shell:

person = Person.objects.get(...)
print(person.name)

When we access the attribute, django is actually asking the database for the information and this generates a query to get the value.

The value isn't ACTUALLY stored on the model object itself.

With that in mind, inherently, django models ARE NOT dataclasses. They are plain old regular classes.

CodePudding user response:

Django does not work with data classes. You can define a custom model field. But likely this will take some development work.

  • Related