0

Using MongoAlchemy, is it possible to have a DocumentField that can be one of two types? E.g:

class A(Document):
    foo = StringField()

class B(Document):
    bar = StringField()

class C(Document):
    child = DocumentField(A or B)

I thought of a few options that might work:

  • Give A and B a common parent and then do child = DocumentField(CommonParent).
  • Write a custom Field that overrides DocumentField, but changes the validator to search through a list of types, instead of one.
  • Just use an AnythingField. Kinda defeats the point.

But wondered if it was already done?

Jon G
  • 1,656
  • 3
  • 16
  • 42

1 Answers1

0

There was a branch that I never merged (although I did use it for a while) where I implemented polymorphic types:

https://github.com/jeffjenkins/MongoAlchemy/tree/poly-queries

If you're willing to do a bit of bug fixing that's a pretty good option.

Otherwise the easiest thing to do is implement a custom field. I suspect it might be easier to create a regular field that took a list of DocumentFields as inputs and which could distinguish than to mess with DocumentField (which is sort of what the polymorphism branch does, but more complexly).

Jeff Jenkins
  • 158
  • 1
  • 3
  • Thanks for that. The custom field is the route I have been working on. https://gist.github.com/jmgirven/59a363f9aa8392abca80fbe6956c174b . I think the wrap / unwrap is working, but from the DocumentField code, I think I need to implement `dirty_ops` and `subfields` amongst other things. Any pointers? – Jon G Oct 28 '16 at 15:16
  • Only got notified about this today, sorry. So, if I remember correctly dirty ops doesn't work for sub-documents. But that should be okay as long as you aren't trying to do updates of only the fields which changed (which I wouldn't recommend) – Jeff Jenkins Dec 04 '16 at 15:56