mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

when declaring a non-default primary key, why cant I access it by the name of the field?

Open vahana opened this issue 10 years ago • 2 comments

if I have gid = mongo.ObjectIdField(primary_key=True)

I can access it only using "id" or "pk", but not its own name.

vahana avatar May 11 '16 17:05 vahana

There is a huge internal dependance on the existence of "id" and "pk", such that if the field marked as primary_key weren't renamed, pretty much everything would explode.

Since your example here is… basically the stock default use for _id, there's a trick I use to allow for this kind of re-naming:

class Foo(Document):
    gid = ObjectIdField(db_field="_id")

This assigns the gid attribute name to point at the actual _id field db-side. Note this is still a terrible idea. From the Zen of Python: there should be one, and preferably only one, right way to do something. Since MongoDB requires the primary key be called _id, why not stick to MongoEngine's default id (saving typing the _ all the time)?

amcgregor avatar Jun 23 '16 14:06 amcgregor

Not sure when but this got fixed so accessing it by "gid" would work

bagerard avatar Sep 23 '24 19:09 bagerard