【问题标题】:Django: convert .count value returned to intDjango:将.count值转换为int
【发布时间】:2013-10-11 20:44:34
【问题描述】:

我有以下型号:

class Question(models.Model):
    question = models.CharField(max_length=100)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    value = models.CharField(max_length=200)

我想计算给定问题对象的值为“yes”的答案百分比,但我收到错误TypeError int() argument must be a string or a number, not 'method'。 count 不返回 int 数据类型吗?

我的看法:

def questn(request, question_id):
    q = Question.objects.select_related().get(id=question_id)
    qc = q.answer_set.count
    qyc = q.answer_set.filter(value="YES").count
    qycp = ( int(qy) / int(qc) ) * 100
    return render(request, 'base.html', {
        'q':q, 
        'qc':qc, 
        'qyc':qyc,
        'qycp':qycp,
    })

【问题讨论】:

    标签: python django types typeerror percentage


    【解决方案1】:

    你需要调用count:

    qc = q.answer_set.count()
    

    添加() 会调用count 方法。没有它会使qc 引用count 方法本身。

    这是一个例子:

    >>> a = [1, 2, 3, 4]
    >>> a.clear
    <built-in method clear of list object at 0x02172198>
    >>> a
    [1, 2, 3, 4]
    >>> a.clear()
    >>> a
    []
    >>>
    

    如您所见,列表的clear 方法仅在添加() 后才会被调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 2015-04-30
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2012-02-25
      相关资源
      最近更新 更多