mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

The id type of full object and the id type of the lazy object are different

Open Canicio opened this issue 4 years ago • 0 comments

  • Models:
import datetime
import uuid
from mongoengine import *

class Model1(Document):
    id = UUIDField(primary_key=True, default=uuid.uuid4, binary=False)
    attr1 = StringField(required=True)
    attr2 = IntField()
    attr3 = BooleanField()
    creation_date = DateTimeField(default=datetime.datetime.utcnow)
    meta = {
        'db_alias': 'testdb',
        'collection': 'model1'
    }


class Model2(Document):
    id = UUIDField(primary_key=True, default=uuid.uuid4, binary=False)
    attr1 = StringField()
    reference_field = LazyReferenceField('Model1', dbref=True)
    creation_date = DateTimeField(default=datetime.datetime.utcnow)
    meta = {
        'db_alias': 'testdb',
        'collection': 'model2'
    }
  • Insert sample data (NOTE: the Earth object reference the Moon object):
moon = Model1()
moon.attr1 = 'Moon'
moon.attr2 = 22
moon.attr3 = False
moon.save()

earth = Model2()
earth.attr1 = 'Earth'
earth.reference_field = moon
earth.save()
  • If I check that the Earth object references the moon object by comparing ids, the result is that it does not
earth = Model2.objects.get(attr1='Earth')
moon = Model1.objects.get(attr1='Moon')
if earth.reference_field.id == moon.id:
    print('The Earth reference to the Moon')
else:
    print('The Earth does NOT reference to the Moon')
# OUTPUT: The Earth does NOT reference to the Moon    <-- ¿WTF?
  • The cause is that the id type of full object is UUID and the id type of the lazy object is string:
print('Types ids:', type(moon.id), type(earth.reference_field.id))
# OUTPUT: Types ids: <class 'uuid.UUID'> <class 'str'>    <-- the ids have different types!!!!

I can't use LazyReference objects if I can't easily compare ids without doing conversions.

Canicio avatar Dec 16 '21 10:12 Canicio