MongoEngine / MongoEngine/mongoengine
`switch_db` does not dereference properly
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 4.3k
- Forks
- 1.2k
- Avg merge
- 4h 41m
- Merged PRs (30d)
- 11
Description
I found switch_db functionality really handy and decided to tried it out this weekend. The problem is that it seems ReferenceFields are not properly resolved while in switch_db context. Here is what I've tried so far:
class Agency(DocumentModel):
agency_id = db.StringField()
name = db.StringField()
url = db.StringField()
timezone = db.StringField()
lang = db.StringField()
phone = db.StringField()
fare_url = db.StringField()
class Route(DocumentModel):
agency = db.ReferenceField(Agency)
route_id = db.StringField()
short_name = db.StringField()
long_name = db.StringField()
route_type = db.StringField()
desc = db.StringField()
url = db.StringField()
color = db.StringField()
text_color = db.StringField()
def route(self, route_id):
with switch_db(document_models.Route, self.db_name()) as Route:
route = Route.objects.get(route_id=route_id)
assert (isinstance(route.agency, document_models.Agency))
return route
The assertion fails as route.agency returns a Dbref. However, if I remove completely swith_db and setup the initial database as self.db_name(), everything works as expected.
def route(self, route_id):
route = document_models.Route.objects.get(route_id=route_id)
assert (isinstance(route.agency, document_models.Agency))
return route
I even tried several other cases, with and without select_related(). No luck.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the issue with the shown Agency and Route models, using switch_db and a ReferenceField, then trace how ReferenceField dereferencing behaves inside that context. Done means route.agency resolves to an Agency instance under switch_db, while the non-switch_db behavior and select_related cases remain correct.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- mongodb, python
- Domain
- database
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100