Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

custom id #75

Closed
fortunto2 opened this issue Dec 11, 2020 · 2 comments
Closed

custom id #75

fortunto2 opened this issue Dec 11, 2020 · 2 comments

Comments

@fortunto2
Copy link

fortunto2 commented Dec 11, 2020

Hi cool library.
I have a question, perhaps a stupid one.

How to make your own string values id?
I want nice to get such a tree structure.

https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-parent-references/

db.categories.insertMany( [
   { _id: "MongoDB", parent: "Databases" },
   { _id: "dbm", parent: "Databases" },
   { _id: "Databases", parent: "Programming" },
   { _id: "Languages", parent: "Programming" },
   { _id: "Programming", parent: "Books" },
   { _id: "Books", parent: null }
] )

class Catalog(Model):
    id: str
    parent: Optional[str]


TypeError: can't automatically generate a primary field since an 'id' field already exists
@adeelsohailahmed
Copy link
Contributor

adeelsohailahmed commented Dec 18, 2020

Hi @fortunto2

Feel free to ignore if you already solved the issue, but I'm leaving the reference in case someone ends up here in the future.

By default, ODMantic generates an id field itself for every Model. You can see the details here on why it does that.. This is the reason why you're getting an error: ODMantic is trying generate an implicit id field for your Catalog model but it already exists (i.e. defined by you in the model).

To use the id field (or, really, any name for the field you want your primary field to be), you have to do this:

from odmantic import Field, Model

class Catalog(Model):
    id: str = Field(primary_field=True)
    parent: Optional[str] 

@fortunto2
Copy link
Author

@adeelsohailahmed cool, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants