dataclasses-json
dataclasses-json copied to clipboard
Field metadata ignored when calling the dump function
I have an issue where the dump function seems to be ignoring the metadata configuration altogether.
The Python class:
@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass(frozen=True)
class InvoicePaymentsResponse:
payment_id: str
payment_status: Payment.Status
invoice_id: str
invoice_amount_to_pay: Money = field(metadata=money_metadata)
invoice_payment_status: Invoice.Status
The metadata config, which encodes the money object to a dict (this is not dataclass_json's to_dict function):
money_metadata = config(
encoder=lambda value: value.to_dict()
)
How I initialize it:
return InvoicePaymentsResponse(
payment_id=row[InvoicePaymentModel.payment_id],
payment_status=Payment.Status(row[PaymentModel.status]),
invoice_id=row[InvoicePaymentModel.invoice_id],
invoice_amount_to_pay=Money.from_dict(row[InvoicePaymentModel.invoice_amount]),
invoice_payment_status=Invoice.Status(row[InvoiceModel.status]),
)
And finally, when I want to convert invoice_payments (List of InvoicePaymentsResponse) to a list of dict:
response_body = InvoicePaymentsResponse.schema().dump(invoice_payments, many=True)
The result is a list of Python dicts where all other fields have been correctly encoded except invoiceAmountToPay, this field appears with the correct name but still a Money object inside.
If I were to call InvoicePaymentsResponse.to_dict instead, the Money field gets encoded correctly as per the metadata configuration.
I could not figure out why the behaviour was different between to_dict and dump.
This is on version 0.5.4.
Is there any update on this? I'm running into the same issue. Here's my example.
from dataclasses import dataclass, field
from datetime import datetime
from dataclasses_json import config, dataclass_json, LetterCase
from dateutil.parser import parse
from marshmallow import fields
@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class Test:
created_at: datetime = field(
metadata=config(
decoder=parse,
mm_field=fields.DateTime(format='iso')
)
)
if __name__ == "__main__":
test1 = Test.from_json('{"createdAt": "2022-02-05T15:00:36Z"}')
print(test1) # Works fine
test2 = Test.schema().loads('[{"createdAt": "2022-02-05T15:00:36Z"}]', many=True)
print(test2) # Results in "unknown field, createdAt"
I have the same issue @krispharper
and still not yet fixed for letter_case=LetterCase.CAMEL to handle list json data