Replies: 1 comment
-
@scott2b Sorry for late reply and sorry if I misunderstood your problem but maybe you can try this. # example of tables.py
from piccolo.columns.column_types import (
ForeignKey,
LazyTableReference,
Varchar,
)
from piccolo.columns.m2m import M2M
from piccolo.columns.readable import Readable
from piccolo.table import Table
class NewUser(Table):
name = Varchar()
group_user = M2M(LazyTableReference("UserToGroup", module_path=__name__))
@classmethod
def get_readable(cls):
return Readable(template="%s", columns=[cls.name])
class UserGroup(Table):
name = Varchar(default="PUBLIC")
new_user = M2M(LazyTableReference("UserToGroup", module_path=__name__))
@classmethod
def get_readable(cls):
return Readable(template="%s", columns=[cls.name])
# This is our joining table:
class UserToGroup(Table):
user_new = ForeignKey(NewUser)
user_group = ForeignKey(UserGroup)
@classmethod
def get_readable(cls):
return Readable(
template="%s, %s", columns=[cls.user_new, cls.user_group]
) and now we can save new user which belong to the public # example of FastAPI method
@app.post("/save")
async def save_m2m():
user = NewUser(name="John")
await user.save()
await user.add_m2m(UserGroup(), m2m=NewUser.group_user)
return JSONResponse(
{
"message": "Successfully created new user",
}
) UPDATE: I realise now that this solution is no good because with every new user we create new # example of FastAPI method
@app.post("/save")
async def save_m2m():
user_group = (
await UserGroup.select().where(UserGroup.name == "PUBLIC").first()
)
user = NewUser(name="John")
await user.save()
last_user = (
await NewUser.select().order_by(NewUser.id, ascending=False).first()
)
await UserToGroup.insert(
UserToGroup(
user_new=last_user["id"],
user_group=user_group["id"],
)
)
return JSONResponse(
{
"message": "Successfully created new user",
}
) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a concept of groups for users. This is a many-to-many relationship. By default, I want all new users to belong to the "public" group, which is just the row in the groups table named "public".
Looking for ideas about how I might do this. If we had signals, a post-save signal on the User would probably be a good approach. Since signals are not an option, it's looking like a method override on the User. But that's tricky because methods like
save
andinsert
don't actually execute those queries -- they return a sort of proxy object to the execution. So, during the process of creating a user (i.e. within theinsert
method) it seems like there is not a way to get a handle on the new User instance in order to create the default public m2m relationship.Any ideas about how to approach this?
Beta Was this translation helpful? Give feedback.
All reactions