1

I have 2 tables with "one-to-one" relationship.

When I get data from one table I want to include one field from the related table but without "dot notation".

What works:

class UserEntitySchema(db_schema.Schema):
    class Meta:
        fields = ('id', 'username', 'email', 'confirmed', 'created', 'enabled', 'account.status')

I want "account.status" would come as just "status" but I can't figure out how to gain it.

I tried Pluck as @marke suggested but without any result. Anything is wrong here?

class AccountEntitySchema(db_schema.Schema):
    current_status = fields.Str()
    class Meta:
        fields =('current_status',)

class UserEntitySchema(db_schema.Schema):
    status = fields.Pluck(AccountSchema, 'current_status')
    class Meta:
        fields = ('id', 'username', 'email', 'status')

My updated, working solution (thanks @marke!):

class AccountEntitySchema(db_schema.Schema):
    class Meta:
        fields =('current_status',)

class UserEntitySchema(db_schema.Schema):
    account = fields.Pluck(AccountSchema, 'current_status', data_key='status') #<==== data_key will replace the existing field
    class Meta:
        # Fields to expose
        fields = ('id', 'username', 'email', 'account')
mimic
  • 4,897
  • 7
  • 54
  • 93
  • 1
    How about using pluck field: https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.fields.Pluck – marke Feb 09 '20 at 03:14
  • @marke thanks for your suggestion. No result yet :( updated my post, can you have a look if I'm doing something wrong? – mimic Feb 09 '20 at 03:35
  • @marke, thanks a lot, I finally made it work! (If you put your comment as an answer will check it as a solution). – mimic Feb 09 '20 at 19:59
  • 1
    glad to hear that ;P – marke Feb 10 '20 at 19:29

1 Answers1

1

As mentioned in the comments, one can use pluck field: https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.fields.Pluck

marke
  • 1,024
  • 7
  • 20