Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pyright support for pydantic schema fields inherited from django models. #1346

Open
SMorawiec opened this issue Nov 26, 2024 · 0 comments
Open

Comments

@SMorawiec
Copy link

Is your feature request related to a problem? Please describe.
Having tried django-ninja framework I see some issues with type checkers like pyright. Not sure if thats even possible, But I'd appreciate if someone could take a look at it. Or maybe there is any better approach I could take to avoid silencing typecheckers all the time.

Given following django model:

from django.db import models
import uuid

class Location(models.Model):
    id: uuid.UUID = models.UUIDField(primary_key=True)
    name: str = models.CharField(max_length=255)
    description: str = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.name

and following schema:

from ..models import Location
from ninja import ModelSchema

class LocationCreateSchema(ModelSchema):
    class Meta:
        model = Location
        fields = ['name', 'description']

Im having this endpoint implementation:

from ninja import Router
from django.shortcuts import get_object_or_404

router = Router()

@router.get("/locations/{location_id}")
def get_location(request, location_id: str) -> str:
    location = get_object_or_404(Location, id=location_id)
    tmp = LocationReadSchema.from_orm(location)
    return tmp.name

Obviously this example doesn't make sense logic-wise, but shows the problem.
The only workaround I could have think of is either to silence the warning, or write TypeGuard for each and every schema, which add like 10x more boilerplate than schema itself.
Pyright doesnt recognize LocationReadSchema attributes inherited from Location model. I get error:
error: Cannot access attribute "name" for class "LocationReadSchema"

Describe the solution you'd like
I'd love to see the solution that allows to use pyright for ninja projects that can recognize fields of schemas inherited from django models.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant