【问题标题】:Python/DJango Attribute error : Model object has not attribute objectsPython/DJango Attributeerror:模型对象没有属性对象
【发布时间】:2015-11-29 09:51:23
【问题描述】:

forms.py:

from django.db import models
from django import forms
from pset.models import problem , testcases 

class problems(forms.ModelForm):
    class Meta:
        model=problem
        fields=['pcode','pdesc']

class testcases(forms.ModelForm):
    class Meta:
        model=testcases
        fields=['pcode','inp','out']

    def __init__(self,*args,**kwargs):
        super(testcases,self).__init__(*args,**kwargs)
        self.fields['pcode']=forms.ChoiceField(choices=get_list())


def get_list() :
    tup=((x,x) for x in problem.object.values_list('pcode',flat=True))
    return tup

这里有两种模型形式,一种是问题,另一种是测试用例。 我试图在其中包含一个下拉菜单。 因为它试图包含问题模型中的 pcode 列。

但不知道为什么会报错:

/setup/add_cases/ 处的 AttributeError 类型对象“问题”没有属性“对象” 在函数 get_list 中。

如果需要:

模型.py

from django.db import models

# Create your models here. 
class problem(models.Model) :
    pcode=models.CharField(max_length=10,unique=True)
    pdesc=models.TextField() 

    def __str__(self) :
        return self.pcode   

class testcases(models.Model):
    pcode=models.CharField(max_length=10)
    inp=models.FileField(upload_to='testcases',blank=True)
    out=models.FileField(upload_to='testcases',blank=True)

    def __str__(self):
        return self.pcode

如果遗漏了任何细节,我们深表歉意。

【问题讨论】:

    标签: python django django-forms django-queryset


    【解决方案1】:

    这行写错了:

    problem.object.values_list('pcode',flat=True))
    

    您缺少对象中的“s”。

    problem.objects.values_list('pcode',flat=True))
    

    顺便说一句,约定是为您的 Django 模型使用 CamelCase,并让它们单数而不是复数,例如ProblemTestCase 而不是 problemtestcases

    【讨论】:

    • 啊!当错误更早出现时,我自己用对象替换了对象,并且在删除它时和删除它之后,替换显示错误!无论如何谢谢你:)
    【解决方案2】:

    你只是打错了,在你的get_list函数中应该是objects而不是object

    def get_list() :
        tup=((x,x) for x in problem.objects.values_list('pcode',flat=True))
        return tup
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2015-04-28
      • 2021-10-20
      • 2019-05-11
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多