将SQLite转换为Django

时间:2018-10-02 14:16:27

标签: python django django-orm

我想获得所有具有平均投票权的专辑。

SELECT a.*, avg(v._mark) AS voting from musicwebapp_album AS a LEFT JOIN musicwebapp_vote AS v ON v.album_id = a.id GROUP BY a.id;

我实际上不知道如何使用django。

这是我的模型

from django.db import models
from django.contrib.auth.models import User

class Artist(models.Model):
    name = models.CharField(max_length=128)

class Genre(models.Model):
    name = models.CharField(max_length=32, unique=True)

class Album(models.Model):
    name = models.CharField(max_length=64)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, null=False, default=None)
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE, null=False, default=None)
    lend_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True)
    cover = models.CharField(max_length=256, null=True, default=None)

class Vote(models.Model):
    _mark = models.PositiveSmallIntegerField()
    voted_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    album = models.ForeignKey(Album, on_delete=models.CASCADE, null=False)

    def setMark(self, mark):
        if mark <= 0:
            return -1

        if mark > 5:
            return -1

        self._mark = mark
        return sef._mark

    def getMark(self):
        return self._mark

我正在将django 2.1.2与python 3.6.6结合使用。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

考虑您的模型Vote有一个专辑的外键(我想您错过了)作为专辑:

class Vote(models.Model):
    _mark = models.PositiveSmallIntegerField()
    voted_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    album = models.ForeignKey(Album, on_delete=models.CASCADE)

您可以写为:

qs = Album.objects.annotate(voting=Avg('vote___mark'))

这将为您提供专辑的所有属性以及Votes模型的_mark字段的平均值。

现在,查询集的每个相册对象都将具有投票属性,并且可以通过以下方式实现:

for obj in qs:
    average_vote = obj.voting

docs.

中提到了