首页 > 解决方案 > 如何避免 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 个表单并且必须手动创建对象实例。

我在这里错过了什么吗?我应该改用继承吗?我是否应该重复这些字段以获得更简单的表单和视图?任何建议将不胜感激。

标签: djangodjango-modelsdjango-forms

解决方案


看看抽象基类,它提供了一种将公共字段重用于多个表的简洁方法。

你可能会考虑:

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

我不确定使用外键获取地址信息有什么好处,除非您有多个客户/卖家使用相同的地址并且地址需要统一更新。


推荐阅读