2016-03-27 161 views
1

編輯:這些不同類型的人,只是因爲Django的方法:
Django模型:同一個對象的類型,不同的字段類型

request.POST.get("attribute") 

從JSON數據,返回我的Unicode。 的解決方案是在開始



我有一個很大的問題分析這些價值觀,我不明白它從何而來。
在我的分數模型中,爲了保存遊戲分數,我需要在保存前比較當前分數和舊分數的值。我的錯誤是,我的領域的類型是不同的,而我的對象類型是相同的。

也許一些代碼可以解釋:

class Score(models.Model): 
    map = models.ForeignKey(Map, on_delete=models.CASCADE) 
    user = models.ForeignKey(User, on_delete=models.CASCADE) 
    score = models.FloatField() 

    class Meta: 
     unique_together = ('map', 'user') 

    def save(self, *args, **kwargs): 
     try: 
      oldScore = Score.objects.get(map=self.map, user=self.user) 
     except ObjectDoesNotExist: 
      oldScore = None 

     if oldScore is not None: 
      if oldScore.score < self.score: 
       print >> sys.stderr, type(oldScore), type(self) 
       print >> sys.stderr, type(oldScore.score),  type(self.score) 
       oldScore.delete() 
      else: 
       return False 
     super(Score, self).save(*args, **kwargs) 
     return True 

    def __unicode__(self): 
     return str(self.map) + ' - ' + self.user.username + " : " + str(self.score) 

,我怎麼創造得分並保存:

score = Score(map=map, user=user, score=score) 
saved = score.save() 

調試輸出的結果是:

<class 'main.models.score.Score'> <class 'main.models.score.Score'> 
<type 'float'> <type 'unicode'> 

我想比較我的老與新的分數,但我不能因爲這些不同種類。
我知道我可以做一些類型轉換,但我想知道爲什麼會發生這種情況,也許我在某些愚蠢的事情上失敗了:s

ps:我在python 2.7下和Django 1.9.2 謝謝以幫助我:)

+0

您剛剛打印的類型都有,你可以打印值,爲他們每個人的呢? –

+0

你的表單設置如何?那是接受整數域? – karthikr

回答

1

這是模型的元類完成的一些魔術。參見,模型字段被定義爲Field類(或其子,例如FloatField)。但是當你想使用模型的實例時,你不想在.score屬性中擁有FloatField,那麼你希望在那裏有實際的值,對嗎?當模型的實例被創建時,這由ModelBase.__metaclass__完成。

現在,當你正在保存的價值,它是完全OK,那的score類型是unicode - 假設你通過形式接收到的數據,以及所有你接收到的數據是unicode。保存時轉換(並驗證)該值。 Django查看期望的數據類型(float),並嘗試轉換該值。如果這不行,它會引發一個異常。否則,轉換的值將被存儲。

所以你想與做你的保存方法是這樣的:

def save(self, *args, **kwargs): 
    if self.pk: # the model has non-empty primary key, so it's in the db already 
     oldScore = Score.objects.get(self.pk) 
     if oldScore.score > float(self.score): 
      # old score was higher, dont do anything 
      return False 
    super(Score, self).save(*args, **kwargs) 
    return True 
+0

謝謝,問題解決了! – Theo

相關問題