首页 > 解决方案 > 来自 Django 模型的 AttributeError 继承了抽象基础模型

问题描述

我正在尝试制作一个简单的小应用程序,让用户可以跟踪自己的口袋妖怪。每个口袋妖怪都有 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

标签: pythondjango

解决方案


我认为您的清洁功能存在问题。尝试。

 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函数使计数发生在数据库级别。


推荐阅读