python - 来自 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
解决方案
我认为您的清洁功能存在问题。尝试。
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
函数使计数发生在数据库级别。
推荐阅读
- javascript - 为什么我的属性“cursor:progress”在 Js 过渡期间无法正确显示?
- oracle - PL/SQL 中是否有机会将变量的名称作为字符串获取?
- linux - LFS:9.1 - 6.10 readelf 缺少 libdebuginfod.so.1
- google-kubernetes-engine - GKE 上的 Kubernetes 节点重置
- django - 在 Django 中保存多个模型
- python - TypeError:当我运行 locustfile.py
- c++ - C2783:无法推断辅助函数的模板参数
- react-native - React-Navigation-5 : 同一屏幕中的多个 MaterialTopTabNavigator
- c# - 我想使用 naudio 删除 mp3 文件的前 10 毫秒和最后 10 毫秒
- javascript - 是否可以使用 d3 并像 vis.js 一样创建线/曲线?