Reputation: 375
I use SQLAlchemy to define a User
class.
if an user is not logged on my website, I want to identify him as an AnonymousUser
. I want my AnonymousUser
to be a subclass of my normal User
class, with special method (eg. is_anonymous(self): return true
).
Now, there is an anonymous user that I created initially in my database, with (say) id = 0
.
I would like to define AnonymousUser
as a subclass of User
, where the constructor only returns the anonymous user :
class AnonymousUser(User):
def __init__(self):
anonymous_user = User.get_by_id(0)
self.username = anonymous_user.username
self.id = anonymous_user.id
...
but when I create an AnonymousUser
, it does not understand that I don't want a new User
, but only to create an existing User
, and it commits the creation of a new User
to the session, and since the id
has been set to the existing anonymous_user id
it crashes because of the id unicity condition
How can I tell SQLAlchemy to create a User
object using an existing id?
Is there a more elegant way to do what I want?
I know that I could simply define an anonymous_user by using User.get_by_id(0)
, but then I would have to add an is_anonymous
field to my object and have a variable check each time I check whether my user is anonymous (rather than having two distinct classes, one with a trivial implementation is_anonymous: return False
and the other using is_anonymous: return True
Upvotes: 1
Views: 170
Reputation: 2688
A quick suggestion. You can implement your is_anonymous method on the User class like this:
def is_anonymous(self):
return self.id == 0
Upvotes: 1