Django Model Relationship with Multiple Classes

时间:2016-07-11 20:51:06

标签: python django models

Sure the answer's out there but I've struggled to find the search terms! This is my first Django project and I can't seem to come up with a logical model structure...

Domain-->* Region-->* [Domain]Network

Within a Domain there are various Regions and each region can have a number of Networks (that should only be of the underlying Domain specific model, as each Domain has a specific Network layout).
Each Network has it's own specific fields (although also share some common, so could inherit somehow?)

More Domains (and so Networks) will be created in the future so should be able to scale. Regions may overlap (so Region2 may also be in DomainABC) but again Domain-specific Networks will be applied.

Example:

If the Domain is ABC, you should only be able to associate ABCNetworks to Regions within that domain. Likewise the XYZ Domain should contain regions that can only have XYZNetworks.

DomainXYZ:

  • Region1
    • XYZNetwork1
    • XYZNetwork2
    • XYZNetwork3
  • Region2
    • XYZNetwork4
    • XYZNetwork5
  • Region3
    • XYZNetwork6
    • XYZNetwork7

DomainABC:

  • Region101
    • ABCNetwork1
    • ABCNetwork2
    • ABCNetwork3
  • Region102
    • ABCNetwork4
    • ABCNetwork5
  • Region103
    • ABCNetwork6
    • ABCNetwork7

Maybe a drop down when creating the Domain to select the Network model (OneToOne?), that then forces the Region to only be able to create [Domain]Networks?
Or just a complete rethink!?

Code:

class Domain(models.Model):
    domain_name = models.CharField(max_length=20)

    def __str__(self):
        return self.domain_name


class Region(models.Model):
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
    region_name = models.CharField(max_length=20)

    def __str__(self):
        return self.region_name


class XYZNetwork(models.Model):
    region = models.ForeignKey(Region, on_delete=models.CASCADE)
    network_name = models.CharField(max_length=3)
    network_data = models.GenericIPAddressField()
    useless_number = models.IntegerField()
    network_secondary = models.GenericIPAddressField()
    crazy_network = models.GenericIPAddressField()

    def __str__(self):
        return self.network_name


class ABCNetwork(models.Model):
    region = models.ForeignKey(Region, on_delete=models.CASCADE)
    network_name = models.CharField(max_length=3)
    network_data = models.GenericIPAddressField()

    def __str__(self):
        return self.network_name

2 个答案:

答案 0 :(得分:0)

如果我理解了您的问题,我只需为您的Domain添加一些验证。 请参阅:https://docs.djangoproject.com/en/dev/ref/forms/validation/

答案 1 :(得分:0)

回答你的问题"如何继承公共领域"使用' abstract = True'请参阅此示例https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-base-classes