MongoEngine / MongoEngine/mongoengine

GenericReferenceField doesn't validate choices on upsert

Open
#2,618 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

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!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied models and reproducer, comparing validation during save() with the upsert_one() path. Trace how GenericReferenceField choices are handled for upserts; done when an invalid Z reference raises a ValidationError while valid A and B references still create or update entries.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.