@@ -1299,40 +1299,41 @@ def __new__(meta, name, bases, dct):
1299
1299
# If a member tagged with primary_key=True is defined,
1300
1300
# on this class, use that as the primary key and reassign
1301
1301
# the _id member to alias the new primary key.
1302
- pk : Optional [ Member ] = None
1303
- for name , m in dct .items ():
1304
- if name == "_id" or not isinstance ( m , Member ) :
1302
+ pk : Member = cls . _id
1303
+ for name , m in members .items ():
1304
+ if name == "_id" :
1305
1305
continue
1306
-
1307
1306
if m .metadata and m .metadata .get ("primary_key" ):
1308
- if pk is not None :
1307
+ if pk . name != "_id" and m . name != pk . name :
1309
1308
raise NotImplementedError (
1310
1309
"Using multiple primary keys is not yet supported. "
1311
- f"Both { pk .name } and { name } are marked as primary."
1310
+ f"Both { pk .name } and { m . name } are marked as primary."
1312
1311
)
1313
1312
pk = m
1314
1313
1315
- if pk is None :
1316
- pk = cls ._id
1317
- else :
1314
+ if pk is not cls ._id :
1315
+ # Workaround member index generation issue
1316
+ # TODO: Remove this
1317
+ old_index = cls ._id .index
1318
+ if old_index > 0 and pk .index != old_index :
1319
+ pk .set_index (old_index )
1320
+
1318
1321
# Reassign the _id field to the primary key member.
1319
- cls ._id = pk
1320
- members ["_id" ] = pk
1322
+ cls ._id = members ["_id" ] = pk
1321
1323
1322
1324
# Remove "_id" from the fields list as it is now an alias
1323
1325
cls .__fields__ = tuple ((f for f in cls .__fields__ if f != "_id" ))
1324
1326
1325
- # Check that the atom member indexes are still valid after
1326
- # reassinging to avoid a bug in the past.
1327
- member_indices = set ()
1328
- for name , m in members .items ():
1329
- if name == "_id" :
1330
- continue # The _id is an alias
1331
- assert m .index not in member_indices
1332
- member_indices .add (m .index )
1327
+ # Check that the atom member indexes are still valid after
1328
+ # reassinging to avoid a bug in the past.
1329
+ member_indices = set ()
1330
+ for name , m in members .items ():
1331
+ if name == "_id" :
1332
+ continue # The _id is an alias
1333
+ assert m .index not in member_indices
1334
+ member_indices .add (m .index )
1333
1335
1334
1336
# Set the pk name
1335
- assert pk is not None
1336
1337
cls .__pk__ = (pk .metadata or {}).get ("name" , pk .name )
1337
1338
1338
1339
# Set to the sqlalchemy Table
0 commit comments