Othman
Othman

Reputation: 3018

How to create classes in Django model

Since Django is mapping each model to a table. I am not able to create packages in my code. Where I can wrap sections of the class to make it more logical and increase the coupling.

For example

class Employee(models.Model):

    #personal information
    first_name = models.CharField(max_length=20)
    middle_initial = models.CharField(max_length=1)
    last_name = models.CharField(max_length=20)
    dob = models.DateField()

    #job contract information 
    full_time = models.BooleanField()
    hours_per_day = models.PositiveSmallIntegerField()
    #.. and more

What I am trying to do is this

employee.job.is_full_time
employee.job.get_hours_per_day
# and more

However this means that I have to create a new model and connect it with the employee model using OneToOneField. I don't want to do that .. joins in the database are expensive. Is there anyway to create something like this ?

class Employee(models.Model):

    class PersonalInformation: 
        first_name = models.CharField(max_length=20)
        middle_initial = models.CharField(max_length=1)
        last_name = models.CharField(max_length=20)
        dob = models.DateField()

    class Job:
        full_time = models.BooleanField()
        hours_per_day = models.PositiveSmallIntegerField()
        #.. and more

The main key to the answer is to create a model that contain multiple classes which are going to be mapped to one table in the database.

Upvotes: 0

Views: 79

Answers (1)

knbk
knbk

Reputation: 53649

There is no way to do that with just Django. Django models represent flat, relational databases. Extending the model framework to provide functionality beyond what its backend is capable of is unnecessary, and therefore not implemented in the default framework.

There are third-party packages that provide what you want, but as far as I know these packages use database backends that are capable of using such data structures.

Personally I would go with your first example, a flat, single model that represents all my Employee data. Prevent any disambiguity in your field names, and there will be no cost for using a flat model over a nested model.

And remember: premature optimization is a lot more expensive than an join statement.

Upvotes: 2

Related Questions