Eduardo Matsuoka
Eduardo Matsuoka

Reputation: 716

How to avoid repetition in Django model fields?

I have models that share many common fields. For example:

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

To avoid repeating these fields, I have tried to create classes with these common fields and link using 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)

But now it gets very messy if I try to create a ModelForm based on the Customer, as there is only the wallet field in it. To display my other OneToOneFields I have to create multiple forms: a form for the contact information and another for address information, as ModelForms don't simply display these OneToOneFields as a single form. The views get bloated, as I have to validate 3 forms in total and have to manually create the object instances.

Am I missing something here? Should I use inheritance instead? Should I just repeat these fields to have simpler forms and views? Any advice would be greatly appreciated.

Upvotes: 1

Views: 236

Answers (1)

ac2001
ac2001

Reputation: 736

Take a look at abstract base classes, it provides a clean way to reuse common fields to multiple tables.

You might consider:

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

I am not sure what the benefit of using a foreign key for address information is unless you have multiple customers/sellers using the same address and the addresses will need to be updated in unison.

Upvotes: 1

Related Questions