Problem with extra context when creating a response #1278
Unanswered
jannekanerva
asked this question in
Q&A
Replies: 2 comments 1 reply
-
Yoy may need to include your custom attributes into your schema using resolvers. |
Beta Was this translation helpful? Give feedback.
1 reply
-
I think for the moment you can do it like this: class TaskSchema(ModelSchema):
is_favorite: bool
class Meta:
model = Task
fields = ('id', 'name', 'project')
@staticmethod
def resolve_is_favorite(obj, context):
request = context['request']
return obj.id in request.context_favorites # <--------!
@router.get('/', response=OutputSchema)
def tasks(request):
tasks = Task.objects.select_related('Project')
request.context_favorites = [1, 2, 3] # <--------!
return {
"tasks": tasks
} or without context: class TaskSchema(ModelSchema):
is_favorite: bool
class Meta:
model = Task
fields = ('id', 'name', 'project')
@router.get('/', response=OutputSchema)
def tasks(request):
tasks = Task.objects.select_related('Project')
favorites = [1, 2, 3]
tasks = list(tasks) # fetching from db # <--------!
for t in tasks:
t.is_favorite = t.id in favorites # <--------!
return {
"tasks": tasks
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
This is simplified version of my endpoint. I have two Django models:
Then I have a Django Ninja endpoint with the following schemas
This works fine. The returned JSON is a list of Task objects where the project property is just an integer, just the way I want it to be. Like this:
However, I would like to pass extra context for the response serialization so that I can add a boolean property to each returned Task, let's say e.g.
is_favourite
.I tried returning my response using
model_validate
method, but if I use that, I get a validation error.The error I get is the following, repeated for each task in the queryset.
So when I try passing the context, the previous validation starts to fail. I know I'm doing something wrong, but can't figure out what. All I want is to access the extra context and create an additional
is_favourite
field for each of my Tasks.Any ideas how to make this work?
Beta Was this translation helpful? Give feedback.
All reactions