I must be missing something really obvious. But I can't seem to find a way to represent a set using mongoengine.
class Item(Document):
name = StringField(required=True)
description = StringField(max_length=50)
parents = ListField(ReferenceField('self'))
i = Item.objects.get_or_create(name='test item')[0]
i2 = Item(name='parents1')
i2.save()
i3 = Item(name='parents3')
i3.save()
i.parents.append(i2)
i.parents.append(i2)
i.parents.append(i3)
i.save()
The above code will create a duplicate entry for i2 in the parents field of i1. How do you express a foreign key like relationship in mongoengine?
Instead of using append
then using save
and letting MongoEngine convert that to updates, you could use atomic updates and the $addToSet method - see the updating mongoDB docs
So in your case you could do:
i.update(add_to_set__parents=i2)
i.update(add_to_set__parents=i3)
i.update(add_to_set__parents=i2)
Support for addToSet
and each
doesn't currently exist - see: https://github.com/MongoEngine/mongoengine/issues/33
Update:
add_to_set is supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With