2011-05-06 128 views
0

我有這個「工作」模型(如下所示)。與M2M和外鍵關係的Django模型問題

  • 主機和位置之間存在M2M關係(位置有多個主機分配給它)。
  • 我也有位置和時區之間定義(包含時區的位置分配)外鍵關係的時區級

我遇到的問題是,我無法取消註釋「的colo」由於對「位置」的外鍵引用而導致Host類中的項目。 Location類是在Host類之後定義的。但是由於位置類中的「主機」的M2M參考,我無法將位置的定義移到Host類之上。

我在想概念上錯過了什麼嗎?任何幫助將不勝感激!

這裏是我的模型的相關部分:

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) 

回答

0

由於主機僅會一個位置,您可以從主機模型取出locations場或刪除colo,並改變locationslocation = models.ForeignKey(Location)

從一個位置獲取所有的主機,你可以做

location = Location.objects.get(pk=1) 
hosts = location.host_set.all() #returns all hosts for the location 

下面是Django的一個鏈接docs about backwards relationships

+0

啊哈!這正是我需要的。我不應該擔心在模型中定義落後的關係。我應該使用查詢集和過濾器來在需要時在視圖中反轉關係。謝謝!!! – nnachefski 2011-05-06 17:21:56

1

基本上,你不能引用已被定義之前的位置類。所以如果你切換主機和位置類的順序有幫助。然後,多對多關係指的是尚未定義的Host類。但是由於可以在任一表上定義多對多關係,只需將其移至Host類即可。下面是修改後的代碼:

class Timezone(models.Model): 
    name = models.CharField(max_length=32, unique=True) 
    def __unicode__(self): 
     return "%s"%(self.name) 

class Location(models.Model): 
    name = models.CharField(max_length=3, unique=True)  
    tz = models.ForeignKey(Timezone) 
    def __unicode__(self): 
     return "%s"%(self.name) 

class Host(models.Model): 
    name = models.CharField(max_length=32, unique=True) 
    colo = models.ForeignKey(Location, related_name='colocation') 
    locations = models.ManyToManyField(Location, blank=True) #not required 
    def __unicode__(self): 
     return "%s"%(self.name) 
+0

謝謝你的快速反應,但主機將只有一個位置,它駐留在主機託管 – nnachefski 2011-05-06 15:33:54

+0

但是,您在Location類中定義了多對多的關係到Host類? – 2011-05-06 15:43:20

+0

這與您的問題無關,但您可能需要爲您的時區模型檢查django-timezones。它具有一些很好的功能,可以減少與時區有關的一些頭痛問題。 https://github.com/brosner/django-timezones – 2011-05-06 16:31:45

1

你有很多的主機和位置之間一對多的關係,但是,你要的是,只允許主機具有相同的位置,你其實是想一個一個主機之間一對多的關係位置。這是使用您的Host類中的models.ForeignKey聲明的。您只需重新排序代碼,以便Host類出現在Location類後面,以便引用它。你也可以刪除多關係。

class Timezone(models.Model): 
    name = models.CharField(max_length=32, unique=True) 
    def __unicode__(self): 
     return "%s"%(self.name)  

class Location(models.Model): 
    name = models.CharField(max_length=3, unique=True) 
    tz = models.ForeignKey(Timezone) 
    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) 

我不確定最好的方法來做到這一點,所以我只想寫另一個答案。我的第一個回答基本上,允許nnachefski創建他在問題中定義的模型。在閱讀他的評論後,我意識到他確實需要一個與他所定義的模型略有不同的模型。