Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a field dynamically to a CustomUser model inheriting from mongoengine.django.auth.User?

I am using mongoengine with django. I have a CustomUser model inheriting from mongoengine.django.auth.User that defines some fields. I have a field, which is only needed for some users. I don't want this field in every User objects. As mongoengine.django.auth.User is inherited from mongoengine.Document from which CustomUser model is inherited I can't add fields into it dynamically.So I made my CustomUser model to inherit from both mongoengine.django.auth.User and mongoengine.DynamicDocument

from mongoengine.django.auth import User
from mongoengine import DynamicDocument

class CustomUser(User, DynamicDocument):
    # fields

Using this method I am able to dynamically create fields for CustomUser. But I want to know if it is ok to do this. If there are any other better methods available, please suggest. Thanks.

like image 391
Rag Sagar Avatar asked Jan 26 '26 14:01

Rag Sagar


1 Answers

Yes thats totally valid as the mongoengine.django.auth.User class is inheritable.

Alternative approaches might be to extend explicitly for different types of user eg:

class AdminUser(User):
    role = StringField()

Then you can just use:

User.objects(username=blah)

And if that User is an AdminUser it will return the correct class instance

like image 122
Ross Avatar answered Jan 29 '26 02:01

Ross