如何从模型的视图访问序列化器字段?

时间:2019-08-13 10:34:17

标签: python django django-models django-rest-framework django-views

我正在尝试从模型的视图访问模型的Serializer类中的自定义定义的变量。但是,我还没有找到正确的方法。因此,我们将不胜感激。

我尝试仅通过名称取其值,但这并不成功。

我有这个模型:

import matplotlib.pyplot as plt
import time

def refresh(x,y1,y2,y3):
    plt.close('all')

    plt.figure()

    plt.subplot(3,1,1)
    plt.plot(x, y1)
    plt.subplot(3,1,2)
    plt.plot(x, y2)
    plt.subplot(3,1,3)
    plt.plot(x, y3)

    plt.show
    return

plt.ion

A = [1,2,3,4]
B = [15,16,8,2]
C = [8,6,4,7]
D = [5,4,3,1]

while True:
    time.sleep(5)

    refresh(A,B,C,D)

这是模型的序列化器:

class candidates(models.Model):
    id = models.IntegerField(primary_key=True, blank=True)
    name = models.CharField(max_length=255, blank=True, null=True)
    gender = models.CharField(max_length=10, blank=True, null=True)
    skill = models.TextField(blank=True, null=True)
    note = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'candidates'

在序列化程序中,我还有一个自定义字段“ full_duration”,用于存储候选人的完整体验时间(以月为单位)。

最后,这是模型视图的一部分,我遇到了问题:

class CandidatesSerializer(serializers.ModelSerializer):
    experiences = CandidateExperienceSerializer(many=True)
    full_duration = serializers.SerializerMethodField('get_full_duration')

    def get_full_duration(self, candidate):
        sum = 0
        for exp in candidate.experiences.all():
            if exp.work_from is None:
                exp.work_from = now()

            if exp.work_to is None:
                exp.work_to = now()

            sum += int((exp.work_to - exp.work_from).days / 30)
        return sum

    class Meta:
        model = candidates
        fields = ['id', 'name', 'gender', 'skill', 'note', 'full_duration', 
                  'experiences']

我希望输出是候选列表,其full_duration的范围为[min,max],但是我收到以下错误:

django.core.exceptions.FieldError:无法将关键字“ full_duration”解析为字段。选择包括:经历,性别,身份证,姓名,笔记,技能

1 个答案:

答案 0 :(得分:0)

因此,在@dirkgroten的帮助下,我提出了以下解决方案:

cans = []

for c in candidates_list:
    sum = 0
    for exp in c.experiences.all():
        sum += int((exp.work_to - exp.work_from).days / 30)

        if min != 'null' and max != 'null' and min <= sum <= max:
            cans.append(c)
        elif min == 'null' and max != 'null' and sum <= max:
            cans.append(c)
        elif min != 'null' and max == 'null' and sum >= min:
            cans.append(c)

ids = [c.id for c in cans]
candidates_list = candidates_list.filter(id__in=ids)