【发布时间】:2011-04-25 10:36:33
【问题描述】:
我的网站有两种类型的用户;客户和供应商。我最终得到了以下类结构:
class Customer(models.Model):
# stuff specific to customers
class Supplier(models.Model):
# stuff specific to suppliers
class Profile(models.Model): # returned by Django's User.get_profile()
user = models.ForeignKey(User, unique=True)
customer = models.OneToOneField(Customer, null=True, unique=True)
supplier = models.OneToOneField(Supplier, null=True, unique=True)
现在我需要为这些模型添加多个地址:
- 客户和供应商都应该有他们的“用户”地址,所以应该在个人资料中
- 客户也有帐单地址,那么应该在客户中
地址类似于:
class Address(models.Model):
street1 = models.CharField(max_length=100)
street2 = models.CharField(max_length=100)
zipcode = models.CharField(max_length=16)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
我可以看到两种直接的解决方案来重用地址信息:要么通过 Profile 和 Customer 类中的 ForeignKey 引用 Address,要么从 Address 继承 Profile 和 Customer 类。
我可以看到这两种方法的一些优点:
外键
- 将地址数据很好地分组在一个字段后面,而不是“污染”模型
- 未来没有多重继承的风险
继承
- 更轻松地访问字段
- 更少的数据库连接
- 地址在 Django 的管理中自动显示在对象中
你会选择哪一个,为什么?您认为这两种解决方案本质上都是不好的吗?你有没有更好的选择?
【问题讨论】:
标签: django django-models code-reuse