[英]Avoid repetition between Django ModelForm and Django Model
[英]How to avoid repetition in Django model fields?
我有共享許多共同領域的模型。 例如:
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)
但是現在如果我嘗試基於 Customer 創建一個 ModelForm 會變得非常混亂,因為其中只有 wallet 字段。 要顯示我的其他 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
我不確定使用外鍵獲取地址信息的好處是什么,除非您有多個客戶/賣家使用相同的地址並且地址需要同時更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.