0

我正在使用django-rest-framework并将django-taggit标签添加到我的模型中。

我的模型是movie并且book都只有一个标题和标签

from django.db import models
from taggit.managers import TaggableManager


class Movie(models.Model):
    title = models.CharField(max_length=255, unique=True)
    tags = TaggableManager()

    def __str__(self):
        return self.title


class Book(models.Model):
    title = models.CharField(max_length=255, unique=True)
    tags = TaggableManager()

    def __str__(self):
        return self.title

我序列化模型并构建视图

序列化程序.py

from rest_framework import serializers
from taggit_serializer.serializers import (TagListSerializerField,
                                           TaggitSerializer)


from .models import Movie, Book


class MovieSerializer(TaggitSerializer, serializers.ModelSerializer):

    tags = TagListSerializerField()
    
    class Meta:
        model = Movie
        fields = (
            'id',
            'title',
            'tags',
        )


class BookSerializer(TaggitSerializer, serializers.ModelSerializer):

    tags = TagListSerializerField()
    
    class Meta:
        model = Book
        fields = (
            'id',
            'title',
            'tags',
        )

视图.py

from rest_framework import viewsets

from .models import Movie, Book
from .serializers import MovieSerializer, BookSerializer


class MovieViewSet(viewsets.ModelViewSet):
    serializer_class = MovieSerializer
    queryset = Movie.objects.all()


class BookViewSet(viewsets.ModelViewSet):
    serializer_class = BookSerializer
    queryset = Book.objects.all()

这也是我的ulrs.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),

    path('api/', include('apps.movie.urls')),
    path('api/', include('apps.book.urls')),
]
from django.urls import path, include
from rest_framework import urlpatterns

from rest_framework.routers import DefaultRouter

from .views import MovieViewSet, BookViewSet

router = DefaultRouter()
router.register('movie', MovieViewSet, basename='movie')
router.register('book', BookViewSet, basename='book')

urlpatterns = [
    path('', include(router.urls)),
]

例如,我以 json 格式报告两部电影和两本书

## movies

{
    "id": 1,
    "title": "The Lord of the Rings: The Fellowship of the Ring",
    "tags": [
        "epic",
        "fantasy",
        "adventure"
    ]
}

{
    "id": 2,
    "title": "The Lord of the Rings: The Two Towers",
    "tags": [
        "epic",
        "fantasy",
        "adventure"
    ]
}


## books

{
    "id": 1,
    "title": "Harry Potter and the Philosopher's Stone",
    "tags": [
        "fantasy",
        "adventure"
    ]
}

{
    "id": 1,
    "title": "Crime and Punishment",
    "tags": [
        "psychological novel",
        "philosophical novel"
    ]
}

我可以成功地达到这些元素

http://127.0.0.1:8000/api/movie/<id>/
http://127.0.0.1:8000/api/book/<id>/

我想要的是每个标签的页面来查看电影和书籍。

例如到网址

http://127.0.0.1:8000/api/tags/fantasy/

我想

{
    "id": 1,
    "title": "The Lord of the Rings: The Fellowship of the Ring",
    "tags": [
        "epic",
        "fantasy",
        "adventure"
    ]
}

{
    "id": 2,
    "title": "The Lord of the Rings: The Two Towers",
    "tags": [
        "epic",
        "fantasy",
        "adventure"
    ]
}

{
    "id": 1,
    "title": "Harry Potter and the Philosopher's Stone",
    "tags": [
        "fantasy",
        "adventure"
    ]
}

我怎样才能做到这一点?

到目前为止,我得到了标签页面,其中

序列化程序.py

class TagsSerializer(TaggitSerializer, serializers.ModelSerializer):
    
    class Meta:
        model = Tag
        fields = (
            '__all__'
        )

        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

视图.py

class TagsViewSet(viewsets.ModelViewSet):
    serializer_class = TagsSerializer
    queryset = Tag.objects.all()
    lookup_field = 'slug'

但这只会返回带有 id、name 和 slug 的标签。

任何帮助是极大的赞赏!

4

1 回答 1

0

您可以尝试编写继承自generics.ListView该视图的新视图,该视图可以返回经过过滤的序列化实例列表。您需要通过覆盖get_queryset方法来过滤queryset标签名称。url

网址.py

urlpatterns = [
    path('', include(router.urls)),
    path('tags/<slug:tag_name>/', MoviesByTagSlugViewSet.as_view()),
]

视图.py

from rest_framework import generics


class MoviesByTagSlugViewSet(generics.ListView):
    serializer_class = MovieSerializer
    queryset = Movie.objects.all()
    
    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(tags__name=self.kwargs['tag_name'])
于 2021-07-07T18:13:11.423 回答