是否可以通过queryset访问另一个模型的属性?

时间:2017-04-03 13:48:52

标签: python django django-models django-views

我需要在页面中显示一个列表,其中包含各自平均值的候选人,候选人'计算平均值的分数在另一个模型(评估)中,该模型接收的属性分数包含候选人收到的评估笔记和候选人的外键,因此可能有几个"评估& #34;对于同一个候选人,我必须以各自的平均值显示所有候选人,但是候选人"候选人"模板无法访问笔记,因为它们存储在模板"评估"中,然后我想做一个用于查询集的候选者obj.all与候选人并进行计算根据当前结果的平均值,在" Evaluation.objects.all()"的循环中,然后将候选人和他的平均值传递给放置在数组中的字典,到目前为止这很好,它完美无缺,但是我需要在点击候选人时进行重定向(名称和其他信息),但要使用" pk"我想查询集,而不是某些字典?那么,我的问题是什么,我也在"评估"中尝试了查询集。模板,但我无法访问" Evaluation.objects.all()"来自"评估"模板本身可以收集'得分'拿平均值,我真的不知道该怎么做,你有什么建议?

models.py

from django.db import models
from jsonfield import JSONField
from site_.settings import MEDIA_ROOT
from django.core.validators import MaxValueValidator

class Criterion(models.Model):
    label = models.CharField(max_length=100)

    def  __str__(self):
        return self.label

class Candidate(models.Model):
    name = models.CharField(max_length=100)
    e_mail = models.EmailField(max_length=100, default = '')
    github = models.URLField(default = '')
    linkedin = models.URLField(max_length=100, default = '')
    cover_letter = models.TextField(default = '')
    higher_education = models.BooleanField(default = False)
    docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)



    def  __str__(self):
        return self.name


class Evaluation(models.Model):
    candidate = models.ForeignKey(Candidate)
    criterion = models.ForeignKey(Criterion, default='')
    score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
    appraiser = models.ForeignKey('auth.User')

    def  __str__(self):
        return str(self.candidate)

#model de teste
class Teste(models.Model):
    nome = models.CharField(max_length=10)

    def  __str__(self):
        return str(self.nome)

views.py

from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError
import re


def canditate_list(request):
    candidates = Candidate.objects.all()
    evaluation = Evaluation.objects.all()

    context = {
        'candidates': candidates,
        'evaluation': evaluation,
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel  
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:                                            
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0 
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)

html

{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html>
<head>
    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> 
    <link href="{% static 'css/app.css' %}" rel="stylesheet">   
</head>
<body>
    <h1 class="h1t">Lista de Candidatos</h1>
    {% for l in candidates %}
        <p class="tr"><a href="{% url 'candidate_detail' l.pk %}">{{l}}</a></p>
    {% endfor %}

</body>
</html>

1 个答案:

答案 0 :(得分:1)

你可以做到

from django.db.models import Avg

candidate = get_object_or_404(Candidate, pk=pk)
average = Evaluation.objects.filter(candidate= candidate).aggregate(Avg('score'))['score__avg']