I am very new to pymodm, and I am stuck on trying to create a one to many linking using the models included with pymodm. Here is my example code:
connect(f"mongodb://{ip}:{port}/{db_name}", alias='inventory')
class add_as_reference(fields.ReferenceField):
name = fields.CharField
class Meta:
connection_alias='inventory'
class hold_many_references(MongoModel):
name = fields.CharField
my_refs = fields.ListField(add_as_reference)
class Meta:
connection_alias='inventory'
This fails, with the error:
ValueError: field must be an instance of MongoBaseField, not <class ‘pyuniti.common.lib.inventory.inventory.InventoryDB_API.open_db..add_as_reference’>
I see that you must make this an instance of MongoBaseField, but how can I do that, but have the list hold references to other documents?
Any help would be greatly appriecated.
After doing more reading, I have identified multiple issues with my original post. I have come up with a solution, but I feel there should be a better way to manage a list of document ids than what I have come up with. Here is my new code that does allow me to store a list of document ids
`class add_as_reference(MongoModel):
name = fields.CharField()
class Meta:
connection_alias='inventory'
class hold_many_references(MongoModel):
name = fields.CharField()
my_refs = fields.ListField(ObjectIdField())
class Meta:
connection_alias='inventory'
ref1 = add_as_reference('ref1').save()
ref2 = add_as_reference('ref2').save()
hmr1 = hold_many_references('hmr1', [ref1._id, ref2._id]).save()
`
The downside of doing this way is that I have to manually dereference the document ids in my_refs. What I would really like a field type ListOfReferenceField which you could access values from like this:
hmr.my_refs[0].name
Am I missing something basic? I ask as I am surprised this doesn’t exist already.