The Basic Model Structure

We'll go through several iterations while creating the data model. We'll start with the basic model that contains only the object properties and then gradually add functionality as we go along with the administration interface improvements. Listing 5-4 shows the initial code.

_J VirtualHost kt INT

Rescript ion VARC H AR(aMJ) bintf. add Ir es s VA RC HAR ( 200) is defaoIt BOOLEAN is temp lata BOOLEAN

Listing 5-4. The basic model structure from django.db import models

# Create your models here.

class ConfigDirective(models.Model):

name = models.CharField(max_length=200) is_container = models.BooleanField(default=False) documentation = models.URLField(


def __unicode__(self): return class VirtualHost(models.Model):

is_default = models.BooleanField(default=False) is_template = models.BooleanField(default=False, help_text="""Template virtual hosts are commented out in the configuration and can be reused as templates""")

description = models.CharField(max_length=200) bind_address = models.CharField(max_length=200)

directives = models.ManyToManyField(ConfigDirective, through='VHostDirective')

default_mark = ' (*)' if self.is_default else '' return self.description + default_mark class VHostDirective(models.Model):

directive = models.ForeignKey(ConfigDirective) vhost = models.ForeignKey(VirtualHost)

parent = models.ForeignKey('self', blank=True, null=True, limit_choices_to={'directive__is_container': True})

value = models.CharField(max_length=200)

fmt_str = "<%s %s>" if self.directive.is_container else "%s %s" directive_name ='<>') return fmt_str % (directive_name, self.value)

If you followed the examples and explanation in Chapters 3 and 4, this model should be reasonably familiar to you. We define the basic properties of each element along with the ForeignKey objects that define the relationship between the classes.

There is one thing, though, that may not look familiar to you—the many-to-many relationship declaration in the VirtualHost class:

directives = models.ManyToManyField(ConfigDirective, through='VHostDirective')

Why do we have to define this relationship explicitly, if we already defined the VHostDirective class that joins the two entities together? The reason is that this allows us to find the corresponding ConfigDirectives directly from the VirtualHost, without having to get to the VHostDirective objects first.

We could create the database structure from this model, but it'll be empty at this time and therefore not very useful without at least the list of the core Apache module directives. I have created an initial data JSON file that contains the entries for all core module directives. Here's an example of a few entries; you can get the full set from the book's web page at

Was this article helpful?

0 0

Post a comment