如何使用 objects.filter() 将字典过滤为 django rest 框架中的 POST 方法

Posted

技术标签:

【中文标题】如何使用 objects.filter() 将字典过滤为 django rest 框架中的 POST 方法【英文标题】:how to use objects.filter() for filtering a dictionary to a POST method in django rest framework 【发布时间】:2021-12-05 20:23:32 【问题描述】:

模型.py

class Category(models.Model):
    name = models.CharField(max_length=50,null=False, blank=False)

    def __str__(self):
        return self.name

class Photo(models.Model):
    category = models.ForeignKey(Category, on_delete=models.SET_NULL,related_name='category', null= True, blank= False)
    image = models.ImageField(null= False, blank = False)
    description = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.description

序列化器.py

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['name']


class PhotoSerializer(serializers.ModelSerializer):
    category = CategorySerializer(many=False)
    class Meta:
        model = Photo
        fields = ['id','category','image','description']

view.py

from django.http import response
from rest_framework import viewsets
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from rest_framework.views import APIView
from .models import Category, Photo
from .serializers import PhotoSerializer


class DisplayAllViewSet(viewsets.ModelViewSet):
    queryset = Photo.objects.all()
    serializer_class = PhotoSerializer

class DisplayCategoryViseViewSet(APIView):
    serializer_class = PhotoSerializer

    def post(self, request, format=None):
        data = self.request.data
        print(data)
        category = data['category']
        print(category)
        print(category['name'])
        name=category['name']
        queryset = Photo.objects.filter(category=name)
        serializer = PhotoSerializer(queryset, many=True)
        return Response(Serializer.data)

urls.py

from re import I
from django.db import router
from django.urls import path
from django.conf.urls import include
from rest_framework import routers
from .views import DisplayAllViewSet, DisplayCategoryViseViewSet

router = routers.DefaultRouter()
router.register('allImages',DisplayAllViewSet)

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

在 Postman 中:GET 请求 http://127.0.0.1:8000/gallery/allImages

[
    
        "id": 1,
        "category": 
            "name": "Sirsi"
        ,
        "image": "http://127.0.0.1:8000/sunset.jpg",
        "description": "Sunset view point"
    ,
    
        "id": 2,
        "category": 
            "name": "Chickmangluru"
        ,
        "image": "http://127.0.0.1:8000/tiger.jpg",
        "description": "cheeta"
    
]

在 Postman 中:POST 请求 http://127.0.0.1:8000/gallery/category 正文:


    "category":
        "name":"Sirsi"
    

ValueError : 字段 'id' 应该是一个数字,但得到了 'Sirsi'

我无法使用过滤器(类别=名称)映射请求数据 我知道类别是字典,但是我们是否使用字典在过滤器中映射名称(Sirsi)?使用类别明智地检索 api。

期望的结果:


        "id": 1,
        "category": 
            "name": "Sirsi"
        ,
        "image": "http://127.0.0.1:8000/sunset.jpg",
        "description": "Sunset view point"
    ,

提前谢谢你:)

【问题讨论】:

【参考方案1】:

DisplayCategoryViseViewSetpost 方法中,您需要进行两项更改,如下所示。更改在代码中添加为 cmets

class DisplayCategoryViseViewSet(APIView):
    serializer_class = PhotoSerializer
    
    def post(self, request, format=None):
        data = self.request.data
        print(data)
        category = data['category']
        print(category)
        print(category['name'])
        name=category['name']
        queryset = Photo.objects.filter(category__name=name) #Since you are passing name, if you are passing id of the category, you can give category=name
        print(queryset[0])
        serializer = PhotoSerializer(queryset, many=True)
        return Response(serializer.data)  #Typo , Serializer should be serializer

【讨论】:

以上是关于如何使用 objects.filter() 将字典过滤为 django rest 框架中的 POST 方法的主要内容,如果未能解决你的问题,请参考以下文章

Entry.objects.filter() 或 Entry.objects.get() 如何工作?

django模板获取字典项

如何将多个 filter() 查询附加到一个变量中

django查询中模糊的知识点,filter(blog=blog),filter(username=username).first()--这两者只需一招让你分清QuerySet对象,和用户字典对象(代

如何访问 Django 模板列表中的字典?

ORM查询API