Search code examples
pythondjangotype-hinting

Type hints for the generic utility in the Django


def get_or_create_object(self, model : ?(what will be the type?), data: dict) -> ? (what will be the return type):
        try:
            obj, _ = model.objects.get_or_create(**data)
        except model.MultipleObjectsReturned:
            obj = model.objects.filter(**data).first()
        return obj

get_or_create_object(ModelName, data)

What will be the type hint here - as function will get the Model instances dynamically.


Solution

  • You can use models.Model or Type[models.Model] All Django models inherit from models.Model and the model that is sent to the function is of the same type, of course, if you want to say that it is a class and is a subset of this class, you can use Type[models.Model]

    from typing import Type
    from django.db import models
    
    def get_or_create_object(model: Type[models.Model], data: dict) -> models.Model:
        try:
            obj, _ = model.objects.get_or_create(**data)
        except model.MultipleObjectsReturned:
            obj = model.objects.filter(**data).first()
        return obj
    

    note: get_or_create is exist in Django build-in:

    exp = Example.objects.get_or_create(**data)