Override mongoengine query mechanism

Let's say that I have 2 mongo collections, being handled using mongoengine at server.

class UserA(Document):

  first_name = fields.StringField()
  last_name = fields.StringField()
  country = fields.StringField()

class UserB(Document):  # completely independent of UserA at storage layer
  full_name = fields.StringField()
  country = fields.StringField()

UserA and UserB are 2 separate collections (stored separately in database) having separate entries and have nothing to do with each other at the storage layer.

UserA can be converted to UserB with this formula at compute (server) layer.

def convert_to_userb(user_a):
  user_b = UserB()
  user_b.full_name = user_a.first_name + " " + user_b.last_name
  user_b.country = user_a.country
  return user_b

Now, for some reason I want to override the objects() call in mongoengine of UserB to also fetch data from UserA. Something like

@queryset_manager
def objects(doc_cls, queryset):
  actual_results = <Some form of UserA.objects(query_set)> # result that one would get normally without any override
  additional_results = convert_to_userb(<Some form of UserA.objects(query_set)>)
  return actual_results + additional_results

What's the best way to achieve this? Any particular reason why you would recommend against it, if any?

Back to Top