首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Django模型继承抽象基模型的AttributeError

从Django模型继承抽象基模型的AttributeError
EN

Stack Overflow用户
提问于 2020-07-29 15:35:11
回答 2查看 88关注 0票数 0

我正试图建立一个简单的小应用程序,让用户跟踪他们自己的口袋妖怪。每个口袋妖怪有1-2种不同的“类型”(如火、水等),所以我增加了一个clean函数来限制用户可以选择的类型的最大数量。但是,在尝试添加口袋妖怪时,会出现以下错误:

/admin/pokollector/custompokemon/add/的AttributeError

'CustomPokemon‘对象没有属性'poke_types'

我假设这与poke_types变量没有被正确继承有关,但我不知道为什么会这样。

下面是我的models.py文件中的代码:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2020-07-29 15:39:57

我想你的清洁功能有问题。试试看。

代码语言:javascript
复制
 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函数,以便在数据库级别上进行计数。

票数 2
EN

Stack Overflow用户

发布于 2020-07-29 15:43:41

刚刚输入了一些带有属性名称的输入,并在len()调用中进行了比较。

代码语言:javascript
复制
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.')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63157220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档