I have helper function for Django views that looks like this (code below). It returns None or single object that matches given query (e.g. pk=1
).
from typing import Type, Optionalfrom django.db.models import Modeldef get_or_none(cls: Type[Model], **kwargs) -> Optinal[Model]:try:return cls.objects.get(**kwargs)except cls.DoesNotExist:return None
Supose I have created my own model (e.g. Car
) with its own fields (e.g. brand
, model
). When I asign results of get_or_none
function to a varibale, and then retriveing instance fields, I get annoying warning in PyCharm of unresolved reference.
car1 = get_or_none(Car, pk=1)if car1 is not None:print(car1.brand) # <- Unresolved attribute reference 'brand' for class 'Model'
What's the propper type hinting to get rid of this warning and get code completion for variable)?