strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
MIT License
394 stars 115 forks source link

returning django model causes typing error #349

Closed hyusetiawan closed 10 months ago

hyusetiawan commented 10 months ago

returning a django model instance in a query, results in a typing error, example for a model called Chat, for an graphql called ChatObject Expression of type "Chat" cannot be assigned to return type "ChatObject" "Chat" is incompatible with "ChatObject" the type checker is pylance

Describe the Bug

given the following mutation:


@strawberry.type
class MutationChat:
    @strawberry.field
    async def create_chat(self, title: str, info: AppInfo) -> ChatObject:
        user = await get_user_from_request(info)
        return await ChatModel.objects.acreate(author=user, title=title)

and the ChatObject is:

@strawberry_django.type(models.Chat, name="Chat") class ChatObject(Node): title: auto model: auto

The code runs fine, but the typing is reporting errors, like so:
<img width="681" alt="Screenshot 2023-08-27 at 11 52 47 PM" src="https://github.com/strawberry-graphql/strawberry-graphql-django/assets/1062920/c5e14a83-cc6c-45d3-93b4-37d198c33b48">

<!-- A clear and concise description of what the bug is. -->

## System Information

 - Operating system: macos
 - Strawberry version (if applicable):

strawberry-graphql==0.205.0 strawberry-graphql-django==0.16.0


## Additional Context

<!-- Add any other relevant information about the problem here. -->

<!-- POLAR PLEDGE BADGE START -->
## Upvote & Fund

- We're using [Polar.sh](https://polar.sh/strawberry-graphql) so you can upvote and help fund this issue.
- We receive the funding once the issue is completed & confirmed by you.
- Thank you in advance for helping prioritize & fund our backlog.

<a href="https://polar.sh/strawberry-graphql/strawberry-graphql-django/issues/349">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/strawberry-graphql/strawberry-graphql-django/issues/349/pledge.svg?darkmode=1">
  <img alt="Fund with Polar" src="https://polar.sh/api/github/strawberry-graphql/strawberry-graphql-django/issues/349/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->
bellini666 commented 10 months ago

Hi @hyusetiawan ,

This is a known issue and unfortunately we don't have a way to solve this elegantly yet.

As I mentioned in this comment, I'm planning to add PEP 712 support to strawberry so that we may be able to workaround this in the future. In the meantime you can workaround this by doing return cast(CharObject, await ChatModel.objects.acreate(author=user, title=title))

I'm gonna close this as it is duplicated of #256 . Feel free to add more thoughts into that issue :)