sbdchd / django-types

:doughnut: Type stubs for Django
MIT License
188 stars 62 forks source link

JSON field is partially unknown, JSONField[Unknown] #116

Open argilya opened 2 years ago

argilya commented 2 years ago

Hello,

I am having an issue with Pyright flagging JSON fields on my models as partially unknown. The way I define my models is like so:

class Config(models.Model)

    id = models.AutoField(primary_key=True)
    settings = models.JSONField(default=empty_json) # the Pyright error occurs here

The error is reportUnknownVariableType and reveal_type of "settings" variable is JSONField[Unknown].

I poked around the stub file, and I see that the return type is JSONField[_A] or JSONField[Optional[_A]]. I am still trying to wrap my head around generics. Is _A a type I should provide when I define the field?

I naively tried specifying type of the field like so:

settings = models.JSONField[UserConfig](default=empty_json)

where UserConfig is the dataclass that houses the data in the controller layer. Doing this removes the Pyright error (the type is now JSONField[UserConfig]), but it makes the code crash when I try to run. The interpreter error is TypeError: 'type' object is not subscriptable.

So I've tried doing it this way:

settings: models.JSONField[UserConfig] = models.JSONField(default=empty_json)

and that worked! Pyright is happy, and the code executes. Is this the correct way to type JSONFields? The syntax is a big ugly, and I feel like I am missing something about generics.

Thank you!

ryanking commented 1 year ago

@argilya I ran into the same issue and was able to resolve by adding JSONField to the list of classes I monkeypatched, as described here.