【发布时间】:2017-02-16 23:43:58
【问题描述】:
我有 2 个模型:作者和评论。我需要获取按 author_id 过滤的 cmets 列表!像这样的:
- api/authors/author_id/cmets
- 或者这个:api/cmets?author_id=author_id
- 或者这个:api/cmets/author/author_id
这里是官方文档:http://www.django-rest-framework.org/api-guide/filtering
这里有类似的问题:Filtering in django rest framework
这对我没有帮助。不幸的是,互联网上没有这个任务的完整简单示例。
请告诉我,我应该在我的代码中更改什么来执行此过滤?
我的代码:
# models.py
from django.db import models
from django.utils import timezone
class Author(models.Model):
name = models.CharField(max_length=200)
class Comment(models.Model):
author = models.ForeignKey('Employee', related_name='author_comments')
text = models.TextField(blank=True)
published = models.BooleanField(default=True)
# serializer.py
from rest_framework import serializers
from core.models import Author, Comment
class AuthorSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Author
fields = '__all__'
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = '__all__'
# views.py
from rest_framework import viewsets
from models import Author, Comment
from serializers import AuthorSerializer, CommentSerializer
class CommentViewSet(viewsets.ModelViewSet):
queryset = Club.objects.all()
serializer_class = ClubSerializer
# urls.py
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'comments', views.CommentViewSet)
【问题讨论】:
标签: python django django-rest-framework