Skip to content
This repository has been archived by the owner on Feb 17, 2023. It is now read-only.

Use recursive method to correctly handle one_to_many fields #1

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

pedro-prose
Copy link

Given:

class LabelSchema(ModelSchema):
    class Config:
        model = OrderItemLabel
        include = ['value']

class OrderItemSchema(ModelSchema):
    label: LabelSchema | None
    quantity: int

    class Config:
        model = OrderItem
        include = ['label', 'quantity']

class CustomerSchema(ModelSchema):
    class Config:
        model = Customer
        include = ['username']

class OrderSchema(ModelSchema):
    items: list[OrderItemSchema]
    customer: CustomerSchema
    
    class Config:
        model = Order
        include = ['items', 'customer']

When calling:

OrderSchema.from_django(order).dict()

Will return:

 {
    'items': [
        {'quantity': 1, 'label': None},
        {'quantity': 1, 'label': None},
        {'quantity': 1, 'label': 1}
    ],
    'customer': {'username': 'exemple@gmail.com'}
}

Note that label = 1, the ID and not the value (str) expected from LabelSchema.

With this PR change, the new output is:

{
    'items': [
        {'quantity': 1, 'label': None},
        {'quantity': 1, 'label': None},
        {'quantity': 1, 'label': {'value': 'Product 10'}}
    ],
     'customer': {'username': 'c@i.com'}}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant