简体   繁体   English

Django 中的同一 model 中具有更多字段的不同用户

[英]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.我计划为两个不同的用户使用同一个用户 model,在一个 model 中添加一些附加字段。 Is it possible to do this in Django?是否可以在 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.您创建一个新的 Model(称为 ExtendedUser)并将额外的字段放入该 model 中。 You then set your ExtendedUser model to inherit from your MainUser model.然后将 ExtendedUser model 设置为从 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.这样做的好处是您的 ExtendedUser model 将继承您原始 MainUser model 中定义的任何方法,并且您只需要向 ExtendedUser model 添加方法,如果您绝对有的话。 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.您还可以编写可以轻松处理 MainUser 和 ExtendedUser 模型的函数,因为它们都是 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.使用继承的好处之一是,如果您在 ExtendedUser model 上编写查询以获取所有字段,它也可以很好地获取 MainUser 字段。

A Second (worse) option:第二个(更糟糕的)选项:

Have a single extended model with a flag on it which says whether to use the extra fields.有一个扩展的 model,上面有一个标志,表示是否使用额外的字段。 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.注意:在 SQL 中拥有第二个表与两者之间的关系并不是一件坏事——这就是通常管理数据的方式。 Having special optional fields for some types of users isn't great as mentioned.如前所述,为某些类型的用户提供特殊的可选字段并不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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