我正试图建立一个简单的小应用程序,让用户跟踪他们自己的口袋妖怪。每个口袋妖怪有1-2种不同的“类型”(如火、水等),所以我增加了一个clean函数来限制用户可以选择的类型的最大数量。但是,在尝试添加口袋妖怪时,会出现以下错误:
/admin/pokollector/custompokemon/add/的AttributeError
'CustomPokemon‘对象没有属性'poke_types'
我假设这与poke_types变量没有被正确继承有关,但我不知道为什么会这样。
下面是我的models.py文件中的代码:
from django.db import models
from django.core.validators import MinValueValidator as min, MaxValueValidator as max
from django.core.exceptions import ValidationError
class PokeType(models.Model):
poke_type = models.CharField(max_length=15)
def __str__(self):
return self.poke_type
#Current generation of games for gen_added field
gen = 8
class Pokemon(models.Model):
poke_name = models.CharField(max_length=30)
poke_type = models.ManyToManyField(PokeType)
evolves_from = False
evolves_into = False
gen_added = models.PositiveIntegerField(validators=[min(1), max(gen)])
def clean(self):
#Allow max of 2 poke_types to be selected
if len(self.poke_types > 2):
raise ValidationError('A Pokemon has a maximum of two types.')
class Meta:
verbose_name_plural = 'Pokemon'
abstract = True
class CustomPokemon(Pokemon):
name = models.CharField(max_length=30)
level = models.PositiveIntegerField(blank=True, null=True)
def __str__(self):
return self.name发布于 2020-07-29 15:39:57
我想你的清洁功能有问题。试试看。
def clean(self):
#Allow max of 2 poke_types to be selected
if self.poke_type.count() > 2:
raise ValidationError('A Pokemon has a maximum of two types.')好像你打错了。另外,不要使用len函数。当您使用len时,计数发生在python上,这是一个缓慢的过程。使用count函数,以便在数据库级别上进行计数。
发布于 2020-07-29 15:43:41
刚刚输入了一些带有属性名称的输入,并在len()调用中进行了比较。
def clean(self):
#Allow max of 2 poke_types to be selected
if len(self.poke_type) > 2:
raise ValidationError('A Pokemon has a maximum of two types.')https://stackoverflow.com/questions/63157220
复制相似问题