[我的models.py看起来像
class Article(models.Model):
article_type = models.ForeignKey(
ArticleType,
null=True,
on_delete=models.CASCADE,
related_name='articles'
)
title = models.CharField(
max_length=100,
verbose_name='Article Title'
)
和urls.py
router = DefaultRouter()
router.register('article', ArticleViewSet, basename='article')
urlpatterns = [
path('viewset/', include(router.urls)),
]
现在我将不列出所有'article_type = None'的文章,并通过点击进行更新
http://127.0.0.1:8000/viewset/article/unmapped
有没有办法做到这一点?
这可以使用ViewSet actions来实现。该实现将遵循以下方式:]
@MathewHegarty的答复有帮助,但我通过]解决了>
@action(detail=False, methods=["GET"], url_path='unmapped')
def unmapped(self, request):
articles = self.queryset.filter(article_type=None)
serializer = self.get_serializer(articles, many=True)
return Response(serializer.data)
@action(detail=True, methods=["GET"], url_path='unmapped')
def ret_map(self, request):
obj = get_object_or_404(self.queryset, pk=pk)
return Response(status=status.HTTP_200_OK)
@ret_map.mapping.put
def map(self, request):
#code for 'PUT'