如何将待处理任务数添加到列表Json

时间:2019-03-20 09:12:22

标签: django django-rest-framework

我正在django rest框架中创建待办事项列表API(后端)。我有两个模型List和Task

#models.py

from django.db import models

# Create your models here.
class List(models.Model):
    list_name = models.CharField(max_length=200)

    def __str__(self):
        return self.list_name

    class Meta:
        db_table = 'list'


class Task(models.Model):
    todo_list = models.ForeignKey(List, on_delete=models.CASCADE)
    task_name = models.CharField(max_length=500)
    due_date = models.DateField()
    done = models.BooleanField(default=False)

    def __str__(self):
        return self.task_name

    class Meta:
        db_table = 'task'

序列化器文件

#serializers.py
from rest_framework import serializers
from rest_framework_serializer_extensions.serializers import SerializerExtensionsMixin
from .models import List, Task


class ListSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    class Meta:
        model = List
        fields = "__all__"

class TaskSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = "__all__"
        expandable_fields = dict(
            todolist=ListSerializer
        )

我的待办事项列表应用程序将有多个列表,每个列表都有多个任务。每个任务都有截止日期,可以标记为已完成。我正在尝试将待处理任务的数量添加到我的List json中。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用SerializerMethodField添加新字段:

class ListSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    pending_count = serializers.SerializerMethodField()
    class Meta:
        model = List
        fields = "__all__"

    def get_pending_count(self, obj):
       return obj.task_set.filter(done=False).count()