在DRF中添加链接到序列化程序中的操作的url字段

我正在使用 django rest 框架。我想在其序列化程序中包含视图中定义的操作的 URL。

我正在使用 django rest 框架。我想在其序列化程序中包含视图中定义的操作的 URL。

Myserializers.py:
from rest_framework import serializers
    
cl CommentSerializer(serializers.ModelSerializer):
    """Serializer for comments."""
    
    cl Meta:
        model = Comment
        fields = ["id", "item", "author", "content", "date_commented", "parent"]
    
    
cl ItemDetailSerializer(serializers.ModelSerializer):
    """Serializer for items (for retrieving/detail purpose)."""
    
    category = CategorySerializer(many=True, read_only=True)
    media = MediaSerializer(many=True, read_only=True)
    brand = BrandSerializer(many=False, read_only=True)
    specifications = serializers.SerializerMethodField(source="get_specifications")
    comments = ??????????????????????????????????????????????????
    
    cl Meta:
        model = Item
        fields = [
            "id",
            "slug",
            "name",
            "description",
            "brand",
            "show_price",
            "location",
            "specifications",
            "is_visible",
            "is_blocked",
            "created_at",
            "updated_at",
            "seller",
            "category",
            "media",
            "comments",
            "users_wishlist",
            "reported_by",
        ]
        read_only = True
        editable = False
        lookup_field = "slug"
    
    def get_specifications(self, obj):
        return ItemSpecificationSerializer(obj.item_specification.all(), many=True).data
Myviews.py:
from rest_framework import viewsets, mixins, status
from ramrobazar.inventory.models import Item, Comment
from ramrobazar.drf.serializers ItemSerializer, ItemDetailSerializer, CommentSerializer
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
    
cl ItemList(viewsets.GenericViewSet, mixins.ListModelMixin):
    """View for listing and retrieving all items for sale."""
    
    queryset = Item.objects.all()
    serializer_cl = ItemSerializer
    serializer_action_cles = {
        "retrieve": ItemDetailSerializer,
    }
    permission_cles = [IsAuthenticatedOrReadOnly]
    lookup_field = "slug"
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_fields = [
        "category__slug",
        "brand__name",
    ]
    search_fields = ["name", "description", "category__name", "brand__name", "location"]
    
    def get_serializer_cl(self):
        try:
            return self.serializer_action_cles[self.action]
        except:
            return self.serializer_cl
    
    def retrieve(self, request, slug=None):
        item = self.get_object()
        serializer = self.get_serializer(item)
        return Response(serializer.data)
        
    @action(detail=True, methods=['GET'])
    def comments(self, request, slug=None):
        item = Item.objects.get(slug=slug)
        queryset = Comment.objects.filter(item=item)
        serializer = CommentSerializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

我在ItemList视图中有一个名为comments的动作,该动作给出了特定项目的所有注释。我可以从 url/api/items/<slug>中获取该项目的详细信息。我可以从 urlapi/items/<slug>/comments中获取该项目的所有注释。我想在中包含一个comments字段如何完成a

0

您可以通过SerializerMethodFieldreverse执行此操作:

cl ItemDetailSerializer(serializers.ModelSerializer):
    ...
    comments = serializers.SerializerMethodField(source="get_comments")
    ...
    def get_comments(self, obj):
        return reverse(YOUR_URL_NAME, kwargs={'slug': obj.slug})
0

试试这个:

cl ItemDetailSerializer(serializers.ModelSerializer):
...
    comments = serializers.CharField(max_length=100, required=False)
    def create(self, validated_data):
        validated_data['comments'] = self.context['request'].build_absolute_uri() + 'comments'
        return super(ContentGalleryListSerializer, self).create(validated_data)
0
You can use the HyperlinkedIdentityField for this:
comments = serializers.HyperlinkedIdentityField(
    view_name='item-comments',
    lookup_field='slug'
)
This will then render a comments field that contains a URL to the item-comments view, with the slug as lookup parameter.
You will need to register the view with the name item-comments, for example with:
urlpatterns = [
    path('items/<slug>/comments/', ItemList.as_view({'get': 'comments'}), name='item-comments')
]
Note that normally nested routes are discouraged, and you'd put the comments in a separate view. But the above should work.

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(455)
C++函数和MPI编程
上一篇
检查 DirectX最终用户运行时的注册表
下一篇

相关推荐

  • curl 超时时间设置解决网络请求延迟的最佳实践

    示例示例cURL 超时时间设置是指在 cURL 发出请求后,等待服务器响应的最长时间。如果超过了设定的超时时间,则会收到一个超时错误。可以使用 curl_setopt() 函数来设置 cURL 超时时间,该函数的第一个参数是 cURL 资源句柄,第二个参数是 CURLOPT_TIMEOUT,用于设置 cURL 超时时间。…

    2023-04-27 15:16:10
    0 20 34
  • curl是什么命令:使用curl命令获取网络数据的技巧

    cURL是一种命令行工具,可用于从Web服务器获取数据或将数据发送到Web服务器。它可以用来检索文件,提交表单,检查网站的状态,以及执行其他各种HTTP功能。…

    2023-04-24 14:20:35
    0 17 23
  • curl 压力测试:使用cURL来提高性能

    curl 压力测试是一种利用 curl 命令行工具来模拟多个客户端同时发起请求的压力测试方法,可以帮助开发者检测服务器的性能和稳定性。…

    2023-04-27 04:48:40
    0 60 75
  • curl 耗时如何使用cURL减少网络请求响应时间

    cURL 耗时是指发出一个 cURL 请求所花费的时间,它取决于服务器的响应时间、网络延迟以及其他因素。可以使用 curl_getinfo() 函数来获取 cURL 请求的耗时信息,如下代码:…

    2023-05-30 16:04:54
    0 63 44
  • python urllib2 安装指南,让你的Python程序访问网络

    实例实例Python urllib2 安装非常简单,只需要使用 Python 的包管理器 pip 即可完成安装。安装步骤如下:…

    2023-05-18 07:46:15
    0 81 64
  • curl是什么意思轻松管理远程数据传输

    cURL是一个开源的、跨平台的、命令行工具,用于发出网络请求,它同时支持HTTP、HTTPS、FTP等协议。它可以用来模拟客户端的行为,发出GET/POST请求,也可以用来上传文件、下载文件。…

    2023-04-14 01:33:14
    0 25 69
  • curl 测试使用cURL命令行工具测试您的Web服务

    cURL 测试是一种使用 cURL 命令行工具来测试 HTTP 请求的方法。它可以让开发人员快速地检查网站的响应,而无需打开浏览器。…

    2023-04-13 00:50:52
    0 38 35
  • curl 断点续传使用Curl断点续传实现快速、稳定的下载

    curl 断点续传是指,在下载文件时,如果中途出现网络中断或者其他原因导致下载失败,可以使用 curl 的断点续传功能,从上次下载失败的位置开始继续下载。…

    2023-03-31 12:28:24
    0 31 70

发表评论

登录 后才能评论

评论列表(24条)