mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

GenericReferenceField doesn't validate choices on upsert

Open jayminbpatel opened this issue 3 years ago • 0 comments

Hi, I am trying to use the GenericReferenceField with more than one reference in the choices parameter and use the upsert_one() to update or create a new entry. Below are the example models for understanding.

class A(me.Document): name = me.StringField() meta = {"strict": False}

class B(me.Document): name = me.StringField() meta = {"strict": False}

class Z(me.Document): name = me.StringField() meta = {"strict": False}

class C(me.DynamicDocument): category = me.StringField() object_oid = me.GenericReferenceField(choices=[A, B]) meta = {"strict": True}

Using given models, below code is expected to create a new field if it doesn't exist because the object_oid we save is reference to model A and B as defined in the choices: a_obj = A.objects.get(name='Apple') C.objects(object_oid=a_obj.id).upsert_one({'category': 'C', 'object_oid': a_obj}) b_obj = B.objects.get(name='Banana') C.objects(object_oid=b_obj.id).upsert_one({'category': 'C', 'object_oid': b_obj})

However, the below code has two scenarios where we try to save and upsert entries. As Z is not in the choices of the GenericReferenceField, both of these scenarios should throw a Validation error. However, on calling save() it validates the choices but on calling upsert_one() it doesn't validate. z_obj = Z.objects.get(name='Zebra') i) C(category='Z', device_oid=z_obj).save() // Throws the Validation error ii) C.objects(object_oid=z_obj.id).upsert_one({'category': 'C', 'object_oid': z_obj}) // Doesn't throw a Validation error

Please let me know if this is a bug or is there any other way to validate the GenericReferenceField choices on using upsert()?

Thanks!

jayminbpatel avatar Feb 01 '22 19:02 jayminbpatel