【问题标题】:Django: Different User models with custom fieldsDjango:具有自定义字段的不同用户模型
【发布时间】:2015-05-06 20:29:00
【问题描述】:

我正在开发一个新项目,但在规划用户模型时遇到了一些疑问。

我需要两种用户类型:

  • 客户:客户可以买东西
  • 购物者:商店客户将能够出售商品

这些模型将共享一些基本数据,例如:

  • 地址
  • 电话
  • NIF
  • 还有其他一些...

但每个用户类型也会有自定义字段。

我正计划使用共享字段创建一个新模型 Profile,然后使用 Heritage 实现 2 个子模型 ProfileClientProfileShop自定义字段。

我想知道这是否是最好的方法,或者有更好的方法来做到这一点。

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    我猜一个用户可以同时是客户和购物者,是吗?如果是这样,我建议创建一个 Profile 模型,然后 ClientShopper 有一个外键链接到 Profile强>。在这种方法中,您不需要保存相同的个人资料信息两次。

    【讨论】:

      【解决方案2】:

      最好的方法是主观的,但是为了在将来支持更多的配置文件类型而不每次都添加 Profile 模型的子类,您可以在 Profile 模型上拥有一个 JSONField,其中包含 Profile 类型的任意数据。

      class SharedProfile(models.Model):
          user = models.OneToOneField(settings.AUTH_USER_MODEL)
          address = models.CharField(#..)
          phone = models.CharField(#...) # or phone field, whatever
          # optionally add a preferred profile, or current profile data , and then add properties on the model that get the attributes from the related Profile entry.
          current_profile = models.ForeignKey('foo.models.Profile')
      
      class Profile(models.Model):
          shared_profile = models.ForeignKey(SharedProfile)
          profile_type = models.CharField(choices=PROFILE_CHOICES)
          profile_data = JSONField() # whatever JSONField package you are using 
      

      【讨论】:

        猜你喜欢
        • 2021-04-15
        • 1970-01-01
        • 2014-10-03
        • 2011-04-08
        • 2017-03-31
        • 1970-01-01
        • 2021-12-08
        • 2019-08-01
        • 2020-08-13
        相关资源
        最近更新 更多