Closed diegoduncan21 closed 3 years ago
I did it like this and it works! even with nested relations.
from django.http import HttpRequest, QueryDict
request = HttpRequest()
query_dict = QueryDict("", mutable=True)
query_dict.update({"query": "{id, user_id}"})
request.GET = query_dict
MySerializer(my_instance, context={"request": request}).data
If there is a better way of doing it please tell me.
thanks!
For now there's no a better way of doing it other than making HttpRquest object and add a query parameter to it just like you did there because for now django-restql gets a query string from request parameter only unless otherwise you pass a query(parsed one) as a keyword argument to a serializer but it'd still need a request to work thou it's not going to use it. We are thinking of changing it because you are not the first person to ask for something like this so it might actually be useful to some people, I think in the next release we might make 'DynamicFieldsMixin' independent of request and add a way to just pass a query string through kwarg to a serializer.
🔖v0.13.0 is out
Now using DynamicFieldsMixin
outside a view is as easy as
query = "{name, books{title}}" # Your query string
serializer = MySerializer(data, many=True, query=query) # You just need to pass your query string as query kwarg
print(serializer.data)
# This will print
[
{
"name": "Computer Programming",
"books": [
{"title": "Computer Programming Basics"},
{"title": "Data structures"}
]
},
...
]
I want to use the serializer with the queryset and the graph query as string, How can I do this?
thanks!