django 自定义manager

django实现自定义manager。来自用在筛选条件查询的时候
代码如下:
models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models


# Create your models here.
class TodoQuerySet(models.QuerySet):
    def incomplete(self):
        return self.filter(is_done=False)

    def heigh(self):
        return self.filter(priority=1)


class NewTodoManager(models.Manager):
    def get_queryset(self):
        return TodoQuerySet(self.model, using=self._db)


class Todo(models.Model):
    content = models.CharField(max_length=250)
    is_done = models.BooleanField(default=False)
    priority = models.IntegerField(default=1)

    objects = NewTodoManager()

views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from poem.models import Todo
import json


# Create your views here.
def get_todo(request):
    heigh_list = Todo.objects.all().heigh()
    return_data = []
    for heigh in heigh_list:
        a_dict = {
            'id': heigh.id,
            'content': heigh.content
        }
        return_data.append(a_dict)
    return HttpResponse(json.dumps(return_data))

你可能感兴趣的:(python-django)