开发者

Inheritance from models.User: how to escape a situation when user data kept in 2 tables in a database?

The situation is: we need a model class storing user profile data (his profession, country, region, city, etc.).

According to official Django documentation we should do something like the next:

...
class MyUser( models.User ):
  profession = models.CharField( max_length = 64 )
  # other fields...
...

The problem is: there are 2 tables as a result of django-admin.py syncdb command in a database. So if we would like to find a user by profession then our search is not so effective! We could search using only one table, but we have to search using two!

I know one not very clean solution when only one table will be created in a database after syncdb: instead of using inherited from models.User class we can do the next to extend existing User class:

# utils.py
class Utils:

    class ClassContributor: 

        @staticmethod
        def contribute_fields( object_class, *fields ):
            for val in fields:                      
                fie开发者_JAVA百科ld_name = val[ 0 ]
                field = val[ 1 ]
                field.contribute_to_class( object_class, field_name )

# models py
user_contributor = Utils.ClassContributor.contribute_fields(    
    User, 
    ( 'profession', models.CharField( max_lenght = 64 ) ),
)

There is one table as a result, but we don't see profession field in Django admin

Does anybody know another solution of 2-tables problem? Thank you.


As recommended in the docs you can use a "user profile" to store additional information about users:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)

    profession = models.CharField( max_length = 64 )
    # other fields...

You can access it by user.get_profile().profession. You still get two tables, but this is the recommended django way. If you are only searching for attributes of the profile, you search only one table.

Aside: Is this search really that expensive in your special usecase? Did you profile it? For me the approach with two tables always has been ok.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜