Django模型:相同的对象类型,不同的字段类型
编辑:这些不同的类型只是因为django方法:Django模型:相同的对象类型,不同的字段类型,django,python-2.7,Django,Python 2.7,编辑:这些不同的类型只是因为django方法: request.POST.get("attribute") 从Json数据返回unicode。 解决方案是在开始时解析这些值 我有一个大问题,我不明白它从哪里来 在我的分数模型中,为了保存游戏的分数,我需要在保存之前比较当前分数和旧分数的值。我的错误是,我的字段类型不同,而我的对象类型相同 也许一些代码可以解释: class Score(models.Model): map = models.ForeignKey(Map, on_d
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)
调试结果将打印:
<class 'main.models.score.Score'> <class 'main.models.score.Score'>
<type 'float'> <type 'unicode'>
我想把我的旧成绩和新成绩进行比较,但我不能,因为这些不同的类型我知道我可以进行一些类型转换,但我想知道为什么会发生这种情况,也许我在一些愚蠢的事情上失败了:s ps:我在python 2.7和Django 1.9.2下
谢谢你的帮助:)这是模型元类所做的一些魔术。请参见,模型字段定义为
字段
类(或其子类,例如浮动字段
)。但是,当您想要处理模型的实例时,您不希望在.score
属性中有一个FloatField
,您希望在那里有实际值,对吗?这是在创建模型实例时由ModelBase.\uuuu元类\uuuu
完成的
现在,当您保存值时,score
的类型是unicode
——假设您通过表单接收到数据,并且接收到的所有数据都是unicode
。保存时将转换(并验证)该值。Django查看所需的数据类型(float),并尝试转换该值。如果这不起作用,它将引发一个例外。否则,将存储转换后的值
因此,您希望对save方法执行以下操作:
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
您刚刚打印了这两种类型,是否也可以打印每种类型的值?表单设置如何?那是接受整数域吗?
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