django - 如何避免 Django 模型字段中的重复?
问题描述
我有共享许多共同领域的模型。例如:
class Customer(models.Model):
name = models.CharField()
email = models.CharField()
address = models.CharField()
phone = models.CharField()
city = models.CharField()
state = models.CharField()
country = models.CharField()
wallet = models.FloatField()
class Seller(models.Model):
# same fields from Customer class, except the field wallet
为了避免重复这些字段,我尝试使用这些公共字段创建类并使用 OneToOneField 进行链接:
class ContactInformation(models.Model):
phone = models.CharField()
email = models.CharField()
class AddressInformation(models.Model):
address = models.CharField()
city = models.CharField()
state = models.CharField()
country = models.CharField()
class Customer(models.Model):
wallet = models.FloatField()
contact_information = models.OneToOneField(ContactInformation)
address_information = models.OneToOneField(AddresssInformation)
class Seller(models.Model):
contact_information = models.OneToOneField(ContactInformation)
address_information = models.OneToOneField(AddresssInformation)
但是现在如果我尝试基于客户创建一个 ModelForm 会变得非常混乱,因为其中只有钱包字段。要显示我的其他 OneToOneFields,我必须创建多个表单:一个表单用于联系信息,另一个用于地址信息,因为 ModelForms 不会简单地将这些 OneToOneFields 显示为单个表单。视图变得臃肿,因为我必须总共验证 3 个表单并且必须手动创建对象实例。
我在这里错过了什么吗?我应该改用继承吗?我是否应该重复这些字段以获得更简单的表单和视图?任何建议将不胜感激。
解决方案
看看抽象基类,它提供了一种将公共字段重用于多个表的简洁方法。
你可能会考虑:
from django.db import models
class CommonUserInfo(models.model)
name = models.CharField()
email = models.CharField()
address = models.CharField()
phone = models.CharField()
city = models.CharField()
state = models.CharField()
country = models.CharField()
class Meta:
abstract = True
class Customer(CommonUserInfo):
wallet = models.FloatField()
class Seller(CommonUserInfo):
pass
我不确定使用外键获取地址信息有什么好处,除非您有多个客户/卖家使用相同的地址并且地址需要统一更新。
推荐阅读
- c++ - 2D Delaunay,分而治之 - 罕见的错误
- sorbet - 测试设置中声明的变量必须是可空的?
- azure - Azure DevOps - 使用部署组或部署作业发布管道到环境?
- python - 如何使用 tkinter 将回调绑定到列表框?
- android - 我的发布请求的结果是用户的身份验证令牌。我想在应用程序的 TextView 中显示此令牌,但 textview 没有更新
- spartacus-storefront - 多站点场景主题化?
- scala - Spark / Scala:根据当前行中的值变化将行拆分为多行
- pandas - PANDAS:数据框中按其他列分组的列的总和值
- python - 如何在 Python 中计算 .csv 中的项目数?
- c# - Unity C#中文件下载完成后如何调用方法?