我正在关注待办事项教程。我有TodoItem和TodoList,当我进入url`http://localhost:8000/api/todos/时得到它们。我只想从api返回完成的todoItem。我该怎么办
models.py
class TodoList(models.Model):
name = models.CharField(max_length=200, default="blank title")
is_completed = models.BooleanField(default=False)
completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True)
created_at = models.DateTimeField(default=datetime.now(), null=True, blank=True)
#owner = models.OneToOneField(User, on_delete=models.CASCADE)
class Meta:
verbose_name = "Todo List"
verbose_name_plural = "Todo Lists"
ordering = ["name","created_at", "is_completed", ]
def __str__(self):
return self.name
class TodoItem(models.Model):
name = models.CharField(max_length=200, default="blank title")
todo_list = models.ForeignKey(TodoList, on_delete=models.CASCADE, null=True)
description = models.TextField(max_length=200, default="Blank text")
is_completed = models.BooleanField(default=False)
completed_at = models.DateTimeField(default=datetime.now(), null=True, blank=True)
created_at = models.DateTimeField(default=datetime.now(), null=True, blank=True)
deadline = models.DateTimeField(default=datetime.now(), null=True, blank=True)
class Meta:
verbose_name = "Todo List"
verbose_name_plural = "Todo Lists"
ordering = ["created_at", "is_completed","deadline","name" ]
def __str__(self):
return self.name
serializers.py
from rest_framework import serializers
from .models import *
class TodoItemSerializer(serializers.ModelSerializer):
class Meta:
model = TodoItem
fields = '__all__'
class TodoListSerializer(serializers.ModelSerializer):
class Meta:
model = TodoList
fields = '__all__'
views.py
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import *
from .models import *
class TodoItemView(viewsets.ModelViewSet):
serializer_class = TodoItemSerializer
queryset = TodoItem.objects.all()
class TodoListView(viewsets.ModelViewSet):
serializer_class = TodoListSerializer
queryset = TodoList.objects.all()
这是项目级别的 urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from todo import views
router = routers.DefaultRouter()
router.register(r'todos', views.TodoView, 'todo')
router.register(r'todoitems', views.TodoListView, 'todoitem')
router.register(r'todolists', views.TodoItemView, 'todolist')
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('api/', include(router.urls))
]
另一个问题是我需要一个用户登录/注册机制。我已经将所有者属性添加到TodoList(上面已注释)。但是如何列出诸如“向我显示user1的已完成任务”之类的数据呢?
答案 0 :(得分:1)
您的TodoItemView
class TodoItemView(viewsets.ModelViewSet):
serializer_class = TodoItemSerializer
queryset = TodoItem.objects.all()
filter_backends = [DjangoFilterBackend]
filter_class = TodoItemFilter
您的TodoItemFilter
class TodoItemFilter(django_filters.rest_framework.FilterSet):
class Meta:
model = TodoItem
fields = ('is_completed',)
您还可以添加班级的其他字段 在这种情况下,您可以进行http://localhost:8000/api/todos/?is_comploted=true