strawberry-django
strawberry-django copied to clipboard
List of union type field always yields the first type
I declared a field which returns a list of union of Django types (those generated by @strawberry.django.type
). Unfortunately, the returned list only contains elements of the first type stated in a union.
Describe the Bug
There is a generic relation field which relates to multiple data models in my project. So, I would like to create a field which retrieves its related data model instances, ignoring their type.
For example, I have these data models:
- Questionnaire
- AbstractQuestion
- AbstractChoiceQuestion (inherits AbstractQuestion)
- SingleSelectionChoiceQuestion (inherits AbstractChoiceQuestion)
- MultipleSelectionChoiceQuestion (inherits AbstractChoiceQuestion)
- TextQuestion (inherits AbstractQuestion)
A questionnaire question would relate to either a single selection choice question, a multiple selection choice question or a text question. There can be multiple questions in one questionnaire. Therefore, I wrote a method field (using @strawberry.field
) which returns List[ Union[ SingleSelectionChoiceQuestion, MultipleSelectionChoiceQuestion, TextQuestion ] ]
but all I got were a list of SingleSelectionChoiceQuestion
. Should I explicitly construct a corresponding type instance for each data model instance before returning?
The fun part:
- If I were to rearrange the union types order, it always picks the first one.
- I tried this similar trick on
@strawberry.type
, not@strawberry.django.type
, and it worked correctly. See thetest
method in a code below.
System Information
- Operating system: macOS Monterey
- Strawberry version (if applicable): 0.128.0
Additional Context
@strawberry.type
class Test1:
value: int
@strawberry.type
class Test2:
value: int
@strawberry.django.type(models.Questionnaire)
class Questionnaire:
id: strawberry.auto
@strawberry.field
def questions(self) -> List[
Union[
"SingleSelectionChoiceQuestion",
"MultipleSelectionChoiceQuestion",
"TextQuestion"
]
]:
return self.get_questions() # Of course, I checked this method. It returns a list of different question type instances correctly.
@strawberry.field
def test(self) -> List [ Union [ Test1, Test2 ] ]:
return [Test2(value=1), Test1(value=2)]
Upvote & Fund
- We're using Polar.sh 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.
Hey @toddy-corpjurist ,
Both strawberry and strawberry-django have gone through a lot of improvements and bug fixes. Does the newest version still have this issue?
Going to close this as fixed, but please comment here in case it is not