inmate37
inmate37

Reputation: 1238

How to keep DRY while creating common models in Django?

For example I have 2 main models in my django app:

class Employee(Model):
    name = CharField(max_length=50)

class Client(Model):
    title = CharField(max_length=50)

Abstract base class for phones:

class Phone(Model):
    number = CharField(max_length=10)
    class Meta:
        abstract = True

Inherited separate classes for Employee and for Client:

class EmployeePhone(Phone):
    employee = ForeignKey(Employee, on_delete=CASCADE, related_name='employee_phones')

class ClientPhone(Phone):
    client = ForeignKey(Client, on_delete=CASCADE, related_name='client_phones')

It works but I don't like it, I would prefer to keep just one Phone model instead of 3. I know I could use Generic-Models but unfortunately that's not longer an option, because my app is actually REST-API and it seems to be impossible to create Generic-Object while creating Parent-Object. So is there any solution to keep things clean and DRY ?

Upvotes: 1

Views: 290

Answers (3)

Kos
Kos

Reputation: 72299

Other answers present good ideas how you can normalise the database, but if you'd like to keep the schema the same and just avoid repeating the same thing in the code, maybe a custom field subclass is what you're after?

Example:

# fields.py
class PhoneField(models.CharField):
    def __init__(self, **kwargs):
        kwargs.setdefault('max_length', 50)
        ...
        super().__init__(**kwargs)

# models.py
class Employee(models.Model):
    phone = PhoneField()

Upvotes: 1

albar
albar

Reputation: 3100

How about moving EmployeePhone (ClientPhone) as a ManyToManyField in Employee (Client) model related to Phone model?

class Employee(Model):
    name = CharField(max_length=50)
    phones = ManyToManyField(Phone, ...)

Upvotes: 0

chaos
chaos

Reputation: 490

How about keeping 1 Phone class and linking Employee and Customer to Phone via a Foreign Key and removing the abstract :).

Upvotes: 0

Related Questions