2016-03-27 92 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