python - Django 的 NotImplementedError : aggregate() + distinct(fields) not implemented

标签 python django postgresql

我有非常简单的模型:

class Profile(models.Model):
    name = models.CharField(max_length=100, unique=True)
    age = models.IntegerField(default=18)


class Place(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    address = models.CharField(max_length=100, blank=True, null=True)


class ProfilePlaceFeedback(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='feedback_set')
    place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='feedback_set')
    review = models.TextField(blank=True, null=True)
    rating = models.IntegerField(default=0)
    timestamp = models.DateTimeField(auto_now_add=True)

ProfilePlaceFeedback - 是用于存储用户留下的每个评分的模型。 为了计算某些地点 的评分,我需要检索所有最新 用户反馈并对所有评分值求和。下面是检索每个用户的所有最后反馈的代码:

place.feedback_set.order_by('profile', '-timestamp').distinct('profile')

但是进行查询:

place.feedback_set.order_by('profile', '-timestamp').distinct('profile').aggregate(Sum(rating))

引发异常:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/PATH_TO_VIRTUALENV/lib/python3.6/site-packages/django/db/models/query.py", line 357, in aggregate
    raise NotImplementedError("aggregate() + distinct(fields) not implemented.")
NotImplementedError: aggregate() + distinct(fields) not implemented.

使用 Django 2.0 和 postgresql 作为数据库。

请帮我解决这个问题:)

最佳答案

看来你需要这个或类似的东西:

place.feedback_set.values('profile').annotate(rating_sum=Sum(rating)).values('profile','rating_sum').order_by('profile')

关于python - Django 的 NotImplementedError : aggregate() + distinct(fields) not implemented,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814592/

相关文章:

javascript - 在 HTML 中用一条线连接 2 个图像。 Django 模板

sql - Postgresql权限不断失败

sql - 将架构添加到postgresql中的路径

python - 在 Django Url Dispatcher 中获取 http 请求数据?这可能吗?如果是这样,如何?

Python:将字节转换为二进制并移动其位?

python - sqlalchemy,混合属性案例语句

html - Django 服务 CSS 和 HTML

python - 如何旋转数据框

python - 如何使用 Django 从数据库(MySQL)中选择 30 个唯一的随机值?

postgresql - 在 Postgresql 中创建分区表