有关mongodb对象的条件嵌入文档

时间:2016-05-26 23:22:52

标签: python mongodb embedded-documents

我需要帮助思考数据建模(我使用的是python和mongoengine)。我有一个对象,我想根据对象的另一个属性应用不同类的嵌入式文档。

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')

我的问题是,每当我.save()对象时,我都不确定这是如何工作的。也许它开始时太奇怪或复杂了?我愿意接受建议。

1 个答案:

答案 0 :(得分:0)

这听起来像是使用继承的好选择:

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)

另一种选择是覆盖Workout的构造函数并在那里实例化设置,但它不太优雅。