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

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

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

Myserializers.py:
from rest_framework import serializers
    
class CommentSerializer(serializers.ModelSerializer):
    """Serializer for comments."""
    
    class Meta:
        model = Comment
        fields = ["id", "item", "author", "content", "date_commented", "parent"]
    
    
class 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 = ??????????????????????????????????????????????????
    
    class 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
    
class ItemList(viewsets.GenericViewSet, mixins.ListModelMixin):
    """View for listing and retrieving all items for sale."""
    
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    serializer_action_classes = {
        "retrieve": ItemDetailSerializer,
    }
    permission_classes = [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_class(self):
        try:
            return self.serializer_action_classes[self.action]
        except:
            return self.serializer_class
    
    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执行此操作:

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

试试这个:

class 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.

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

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

相关推荐

  • curl 爬虫从入门到精通

    Curl 爬虫是一种从网站上抓取数据的工具,它使用 curl 命令行工具来实现。Curl 爬虫通常用于爬取网页的内容,比如 HTML、XML、JSON 等格式的文件。…

    2023-01-14 01:15:50
    0 25 33
  • curl 获取返回值:利用cURL获取远程数据,实现快速数据交换

    cURL是一个命令行工具,用于从远程服务器获取数据。它使用URL格式来传输数据,并且可以支持多种协议,包括HTTP、HTTPS、FTP等。…

    2023-01-19 11:49:55
    0 26 49
  • curl指令:使用cURL命令行工具获取网页内容

    cURL 是一个能够使用URL语法在命令行下工作的文件传输工具,它是一个开放源代码的软件项目,可以使用HTTP、HTTPS、FTP和FTPS协议来传输数据。…

    2023-01-15 09:13:47
    0 37 24
  • curl put请求:使用curl PUT请求更新资源

    curl PUT请求是使用HTTP协议中的PUT方法发送数据到服务器的一种方式,它的作用是用来更新服务器上的某个资源。它的语法如下:…

    2023-01-12 10:29:35
    0 94 36
  • 粤康码url代码捷径:生成URL的QR码(qr code link)

    关于粤康码url代码捷径的问题,在qr code link中经常遇到,我已经使用 Google 图表和 LGPL QR 码类为 php 生成 URL 的 QR 码,但都无法为下面的 URL 生成正确的:…

    2022-11-26 00:38:34
    0 58 86
  • Curl close:curlCLI到phpcurl

    关于Curl close的问题,在andrew curl中经常遇到,我有一个工作的 CLI…

    2022-11-25 01:29:21
    0 29 21
  • Libcurl编译:Winlibs和 libcurl

    关于Libcurl编译的问题,在winlibs中经常遇到,我在这里问,因为我在其他地方得不到任何支持。也考虑到我是一个初学者,所以要有耐心。…

    2022-12-02 00:17:57
    0 52 56
  • sqlalchemy.exc.ArgumentError:无法从字符串分析 rfc1738URL

    我正在学习烧瓶 Web 微框架,在初始化我的数据库后,我运行flask db init我运行flask db migrate,将我的模型类迁移到数据库,我得到了一个错误。我在 Windows 10 上工作,数据库是 MySQL,扩展安装是flask-migrate,flask-sqlalchemy,flask-login。…

    2022-11-11 15:20:28
    0 93 44

发表评论

登录 后才能评论

评论列表(1条)