2016-05-02 109 views
0

當我嘗試運行,下面的代碼,它是由Django的說:「名字‘卡’沒有定義」Django的模型屬性

class CardSet(models.Model): 

    cards = Card.objects.all() 

    def show_card(self): 

     for card in cards: 
      print(card) 

,但如果我把這樣的代碼,它的工作原理。

class CardSet(models.Model): 

    def show_card(self): 

     cards = Card.objects.all() 
     for card in cards : 
      print(card) 

你能爲我解釋一下嗎?謝謝!它使用self.cards

回答

0

如果這是您的代碼(而不是發佈的代碼至少有一個語法錯誤):

class CardSet(models.Model): 
    cards = Card.objects.all() 
    def show_card(self): 
     for card in cards: 
      print(card) 

這其中有很多問題:

  1. 你不會使用Card.objects.all()但many2many場。有關更多詳細信息,請參閱文檔。否則你的方法就沒有實例方法的意義了。
  2. 該方法中的循環不具有該類的範圍,因爲該範圍僅在您定義類時發生(發生在加載時而不是方法調用時)。
  3. 您的方法涉及self,或許您需要的參考是self.cards而不是cards

推薦碼:

class CardSet(modelsModel): 
    cards = models.ManyToManyField(Card) 
    def show_cards(self): 
     for card in self.cards.all(): 
      print(card) 

OTOH如果cards僅僅是一個類範圍的查詢集,而不是一個M2M關係......

class CardSet(modelsModel): 
    cards = Card.objects.all() 
    def show_cards(self): 
     for card in self.cards: 
      print(card) 

的解決方案是基本相同:添加self

0

訪問:

def show_card(self): 
    for card in self.cards: 
     print (card) 

編輯:我看到了你的另一個問題Relationships among these models in Django

如果保持這種關係,只是查詢中使用相關對象查詢:

cards = models.ManyToManyField(Card) # Ref. this relationship 

def show_card(self): 
    for card in self.cards.all(): # <-- querying for cards related to this 
            # CardSet object 
     print (card) 
+0

感謝您的即時答覆。你們兩個都給了我寶貴的幫助。我很難決定哪一個是最好的答案,我選擇了雷,因爲他比你少點。希望你不介意! 「 –