简体   繁体   中英

Different user with more fields in the same model in Django

I am planning to use a same user model for two different users with some additional fields in one model. Is it possible to do this in Django? If it is possible, how can I do it?

You have two options:

Firstly

You create a new Model (call it ExtendedUser) and you put the extra fields in that model. You then set your ExtendedUser model to inherit from your MainUser model. This will create two tables with a one to one link between them. The advantage of this is that your ExtendedUser model will inherit any methods defined in your original MainUser model, and you only need add methods to the ExtendedUser model if you absolutely have to. You can also write functions which can deal with both the MainUser and ExtendedUser models easily, since they are all instances of the MainUser model. One of the benefits of using inhertiance is if you write a query on the ExtendedUser model fetching all fields, it well fetch the MainUser fields too.

A Second (worse) option:

Have a single extended model with a flag on it which says whether to use the extra fields. This can be made to work, but will make your queries more complex, and if you need the extra fields to be indexed, the indexes are likely to be a bit less efficient.

Note: having a second table with a relationship between the two is no bad thing in SQL - that is how data is normally managed. Having special optional fields for some types of users isn't great as mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM