alexandernst
alexandernst

Reputation: 15089

Creating an union-like related models

I have a Django app with a model called OS (as in "Operating System"). The model has some usual fields, like name or version. Those fields are common to all operating systems.

I also have two other (related) models, called Linux and Windows. Those have some OS-specific fields (Linux has a desktop_environment, as in "KDE" or "Gnome", apps_manager, as in "apt", pacman", etc...; Windows has a built_in_antivirus field, etc...). This means that those two models have completely different fields, that make sense only for specific operating systems.

The OS model has a OneToOne relation with both the Linux and the Windows models, but only one of those 2 actually exists (an OS can't be Linux and Windows at the same time).

How can I create some sort of "relation", "attribute", "manager" or XYZ property so I can access the fields of Linux and Windows from an instance of an OS model?

Example:

a = OS.objects.get(pk=3) # This is a Windows instance
a.<magic>.built_in_antivirus
True

b = OS.objects.get(pk=14) # This is a Linux instance
b.<magic>.desktop_environment

Please note that I don't want to move all fields to the same model.

Upvotes: 0

Views: 32

Answers (1)

Mehak
Mehak

Reputation: 961

You can use a property for this.

You will have to change your models.py:

class OS(models.Model): ''' Your OS Model ''' # your fields go here

@property
def magic_property(self):
    ''' Here is your magic property ''' 
    if hasattr(self, 'linux_related_name'):
        # This has Linux related model
        return self.linux_related_name
    if hasattr(self, 'windows_related_name'):
        # This has Window related model
        return self.windows_related_name
    return None

Now you can access your property using obj.magic_property

Upvotes: 1

Related Questions