Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: PolyModelType that selects Model based on field value of parent #622

Open
Jacco opened this issue Apr 18, 2021 · 1 comment
Open
Labels

Comments

@Jacco
Copy link

Jacco commented Apr 18, 2021

I need to select the model based on a value in the parent model.

'State': {
  'Type': 'Task',
  'Resource': 'TheParentValue',
  'Parameters': {
    'FieldsDependingOnParentValue': 'HowToDoThat?'
  }

Is that possible?

I tried using a claim_function but the data passed is from the same level and not from the parent.

@lkraider
Copy link
Contributor

lkraider commented Aug 24, 2021

Couldn't you match on the parameters content?

from schematics.models import Model
from schematics.types import serializable, StringType, IntType, PolyModelType

state1 = {
    'resource': 'StateType1',
    'parameters': {
        'x': '1',
        'y': '2',
    }
}
state2 = {
    'resource': 'StateType2',
    'parameters': {
        'z': 33,
    }
}

class ParametersType1(Model):
    x = StringType()
    y = StringType()


class ParametersType2(Model):
    z = IntType()

    @classmethod
    def _claim_polymorphic(cls, data):
        return data.get('z')


class StateClaim(Model):
    resource = StringType()
    parameters = PolyModelType([ParametersType1, ParametersType2])

s1 = StateClaim(state1)
s2 = StateClaim(state2)

print(s1, s1._data)
print(s2, s2._data)
<StateClaim instance> {'resource': 'StateType1', 'parameters': <ParametersType1 instance>}
<StateClaim instance> {'resource': 'StateType2', 'parameters': <ParametersType2 instance>}

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

No branches or pull requests

2 participants