A Django Model field with multiple types?

I have the following (simplified) models:

class Structure(models.Model):
name=models.CharField(max_length=100, unique=True)

class Unit(models.Model):
name=models.CharField(max_length=100, unique=True)

Each model also has a builtFrom field that shows what the item is made of, for example:

class Unit(models.Model):
name=models.CharField(max_length=100, unique=True)
builtFrom=models.ForeignKey(Structure)

However, builtFrom can be populated with either a Unit type or a structural type. Is there an easy way to present this in my models?

The only thing I can think of is to have a separate model, for example:

class BuiltFromItem(models.Model):
structure=models.ForeignKey(Structure)
unit=models.ForeignKey(Structure)


class Unit(models.Model):
name=models.CharField(max_length=100, unique=True)
builtFrom=models.ForeignKey(BuiltFromItem)

And then one of the BuiltFromItem fields will be null. Then, when I need data, find out if this is the structure or unit from which it is built. Is there a better solution for this?

+3
source share
2 answers

, Django " ". Django.

+3

, , , , . ModelInline , , ( , " ), ( , ), .

, . , , , BasicObject, Structure Unit :

class BasicObject(models.Model):
    name=models.CharField(max_length=100, unique=True)
    #other common data
    builtFrom=models.ForeignKey('BasicObject')

class Structure(BasicObject):
    #data specific to Structure

class Unit(BasicObject):
    #data specific to Unit

Structure Unit BasicObject, builtFrom BasicObject . , , , .

+1

All Articles