I have this “jobs” model (shown below).
- There is a M2M relationship between Hosts and Locations(A location has multiple hosts assigned to it).
- I also have a Timezone class with a Foreign Key relationship defined between location and timezone(A location is assigned a timezone)
The problem I’m having is that i cannot un-comment the ‘colo’ item in the Host class because of the foreign key reference to “Location”. The Location class is defined after the Host class. But i cannot move the definition of the Location to above the Host class because of the M2M reference for “hosts” in the Location class.
Am i missing something conceptually? Any help would be greatly appreciated!
Here is the relevant part of my model:
class Timezone(models.Model):
name = models.CharField(max_length=32, unique=True)
def __unicode__(self):
return "%s"%(self.name)
class Host(models.Model):
name = models.CharField(max_length=32, unique=True)
# colo = models.ForeignKey(Location)
def __unicode__(self):
return "%s"%(self.name)
class Location(models.Model):
name = models.CharField(max_length=3, unique=True)
hosts = models.ManyToManyField(Host, blank=True) #not required
tz = models.ForeignKey(Timezone)
def __unicode__(self):
return "%s"%(self.name)
Since a Host will only ever have one location, you can remove the
locationsfield from the host model, or removecolo, and changelocationstolocation = models.ForeignKey(Location)To get all hosts from a location, you can do
Here’s a link to the Django docs about backwards relationships