class Related(EmbeddedDocument):
type = StringField()
volume = IntField()
class Main(Document):
name = StringField()
relatives = EmbeddedDocumentListField(Related)
I have a object for Main which has relatives. How can i increment the volume parameter of Related EmbeddedDocument from the Main object.
If I understand your question correctly:
doc = Main.objects.first()
doc.relatives.volume[0] += 1
The above assumes you have at least one item in relatives. To update any/all of them:
doc = Main.objects.first()
for r in doc.relatives:
r.volume += 1
Just FYI, your original is title is more correct. volume is an _instance attribute_ of Related.
Also, if some volume attributes are missing or None, then you might do:
if r.volume
r.volume += 1
else:
r.volume = 1
or to be fancy:
r.volume = 1 + r.volume or 0
Thanks @JohnAD .
If i want to filter the relatives of type "parental" and then increment the volume of the filtered relatives. How can I do that?
I figured out how to filter the relatives based on type
doc.relatives.filter(type='parental')
I am confused how to go further to increment. I tried the following but it didn't help me:
doc.relatives.filter(type='parental').update(inc__volume =1)
The documentation for the update method of EmbeddedDocumentListField is very sparse and does not explain explain what **update means other than _"A dictionary of update values to apply to each embedded document."_
It implies that you can use update methods similar to other functions. But it actually only does replacement. So volume=1 works. It will think inc__volume is a field name rather than an instruction.
The only way to do what you want is with a loop.
for r in doc.relatives.filter(type='parental'):
r.volume += 1
I just did a simple pull request to update the API documentation for added clarity.
I believe this can be closed