1

I need help with thinking about data modeling (I am using python and mongoengine). I have an object that I would like to apply different classes of embedded documents to depending on another attribute the object has.

class RunningSettings(EmbeddedDocument):
    max_distance = DecimalField()
    speed = DecimalField()
    ...

class WeightLiftingSettings(EmbeddedDocument):
    max_weight = DecimalField()
    reps = IntField()
    ...


class Workout(Document):
    name = StringField()
    description = StringField()
    date_created = DateTimeField(default=datetime.utcnow())
    kind = StringField()

    # pseudo starts
    <if self.kind == "running">
    settings = EmbeddedDocumentField('RunningSettings')

    <if self.kind == "weight_lifting">
    settings = EmbeddedDocumentField('WeightLiftingSettings')

My issue is that every time I .save() the object, I'm not sure how this can work. Maybe it is too weird or complicated to begin with? I'm open to suggestions.

Iluvatar14
  • 699
  • 1
  • 5
  • 18

1 Answers1

0

This sounds like a good candidate for using inheritance:

class RunningSettings(EmbeddedDocument):
    max_distance = DecimalField()
    speed = DecimalField()

class Workout(Document):
    name = StringField()
    description = StringField()
    date_created = DateTimeField(default=datetime.utcnow())
    meta = {'allow_inheritance': True}

class RunningWorkout(Document):
    settings = EmbeddedDocumentField(RunningSettings)

Another option is to override the constructor of Workout and instantiate the settings there but it's less elegant.

bagerard
  • 5,681
  • 3
  • 24
  • 48