strawberry-graphql / strawberry-django

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

Returning dict with a datetime isn't compatible with JSON type #429

Closed noamsto closed 7 months ago

noamsto commented 7 months ago

Using JSON type lead to: TypeError: Object of type datetime is not JSON serializable

Describe the Bug

I have a resolver which need to return dictionaries which are not per-defined (read from a DB) Therefore I use list[JSON] type. i.e.:

from strawberry.scalars import JSON

@strawberry.type
class QueryData:
    rows:  list[JSON] | None

For input like this:

[{'store_id': 1,
  'manager_staff_id': 1,
  'address_id': 1,
  'last_update': datetime.datetime(2006, 2, 15, 9, 57, 12)}]

I get the above TypeError: TypeError: Object of type datetime is not JSON serializable

my resolver for reference:

    @strawberry.field
    def execute_query(self, sql_query: str) -> types.QueryData:
        rows = execute(sql_query)
        return types.QueryData(rows=rows)

System Information

Additional Context

Changing the json_encoder class to DjangoJSONEncoder can solve the issue.

It looks like it was done for the other integrations strawberry-graphql/strawberry#2272

Upvote & Fund

Fund with Polar

bellini666 commented 7 months ago

Hi @noamsto ,

I think this makes sense! Do you want to try to open a PR for it? You probably want to override the encode_json method in the django view.

noamsto commented 7 months ago

Sure, I'll try to solve it and make a PR for that

noamsto commented 7 months ago

I have created a PR in Strawberry project: https://github.com/strawberry-graphql/strawberry/pull/3273 If it won't be accepted for some reason, I suggest extend the BaseView in this project maybe? but I don't see a reason they won't accept it.