Home > Software design >  Type hints for the generic utility in the Django
Type hints for the generic utility in the Django

Time:01-17

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.

CodePudding user response:

You can use models.Model All Django models inherit from models.Model and the model that is sent to the function is of the same type

from django.db import models

def get_or_create_object(model: 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)
  • Related