簡體   English   中英

'ProgrammingError:函數avg(字符變化)不存在'-Django Project

[英]'ProgrammingError: function avg(character varying) does not exist' - Django project

我最近將一個Django項目部署到了​​Heroku。 在瀏覽器中測試功能時,嘗試呈現特定模板時遇到了一個新錯誤:

ProgrammingError at /accelerators/6/
function avg(character varying) does not exist
LINE 1: SELECT AVG("reviews_review"."mentorship") AS "avg_mentorship...
           ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

這個問題從來沒有出現在開發服務器中,但是我想我知道問題出在哪里。 我在Accelerator模型中使用Avg,通過確定另一個模型(審閱)的平均輸入平均值(指導)來確定字段的十進制值(avg_mentorship)。

我的指導字段是一個charfield,其中的選擇是數字作為字符串。 我從以下任一模型中都包含了相關代碼:

class Accelerator(models.Model):
    avg_mentorship = models.DecimalField(decimal_places=2, max_digits=3)

    @property
    def avg_mentorship(self):
        quantity = Review.objects.filter(subject=self)
        if len(quantity) > 0:
            mentorship_result = Review.objects.filter(subject=self).aggregate(avg_mentorship=Avg('mentorship'))['avg_mentorship']
        else:
            mentorship_result = 0
        return mentorship_result

class Review(models.Model):
    RATINGS = (
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
    )
    mentorship = models.CharField(choices=RATINGS, blank=False, max_length=1, default='1')

    def save(self, *args, **kwargs):
        self.mentorship = int(self.mentorship)
        super(Review, self).save(*args, **kwargs)

這似乎是一個非常簡單的修復程序,所以我在審查模型中添加了一些將指導轉換為int的代碼。 但是,這還不能解決問題,所以我想知道是否有任何原因導致我的修改后的代碼不起作用,以及我在解釋錯誤消息時是否絕對正確(這不是我的強項)。 任何輸入,不勝感激。 謝謝。

你應該讓mentorshipIntegerField [Django的文檔] (或FloatFieldIntegerField ),如:

class Review(models.Model):
    RATINGS = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
        (5, '5'),
    )
    mentorship = models.IntegerField(choices=RATINGS, default=1)

您無法計算CharField的平均值。 'foo''bar'的平均值是多少? 因此,您需要將數據存儲到數字字段中。

遷移它可能需要一些工作。 如果不需要保留現有數據,我建議您只刪除在其中構建Review模型的遷移文件,然后從此模型和表開始。

請注意,您可以使用以下方法來提高計算聚合的效率:

class Accelerator(models.Model):

    @property
    def avg_mentorship(self):
        return self.review_set.aggregate(
            avg_mentorship=Avg('mentorship')
        )['avg_mentorship'] or 0

在這里,您可以在為您進行的ORM查詢生成的SQL中

LINE 1: SELECT AVG("reviews_review"."mentorship") AS "avg_mentorship...

它正在嘗試計算reviews_review表的mentorship字段的reviews_review AVG期望將整數值作為參數傳遞,因為根據您的模型為其定義的數據類型為CharField,它將引發錯誤。 您可以通過更改mentorship字段的類型來解決此問題。

這樣的事情。

class Review(models.Model):
    RATINGS = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
        (5, '5'),
    )
    mentorship = models.IntegerField(default=1, choices=RATINGS)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM