简体   繁体   English

Django Rest 框架 - 为什么 serializer.data 给我一个空的结果集,但打印序列化器显示数据

[英]Django Rest Framework - Why is serializer.data giving me an empty result set but printing the serializer shows me the data

I have created a view to search posts based on their body text.我创建了一个视图来根据正文搜索帖子。 I added a breakpoint to the view and I tested it with mutliple search terms and it works.我在视图中添加了一个断点,并使用多个搜索词对其进行了测试并且它有效。 The problem I have is when I do a print(serializer) in the console then I see the data of all the posts it found.我遇到的问题是当我在控制台中执行 print(serializer) 然后我看到它找到的所有帖子的数据。 But doing a print(serializer.data) gives me body:null in the data object in the front end console and an empty dictionary in the back end console.但是做一个 print(serializer.data) 在前端控制台的数据 object 中给我正文:null,在后端控制台中给我一个空字典。

I am using PostgreSQL我正在使用 PostgreSQL

Why am I getting body: null?为什么我得到身体:null?

Here is the response in the console for print(serializer):这是打印(序列化程序)控制台中的响应:

SearchSerializer(<QuerySet [<Post: This is a post>, <Post: This is another post>, <Post: Post THREE>, <Post: Post ONE>, <Post: Post ONE by the user>, <Post: Post TWO by the user>]>):
    body = CharField(allow_blank=True, allow_null=True, label='Content', max_length=5000, required=False, style={'base_template': 'textarea.html'})

Here is the view:这是视图:

class SearchPosts(APIView):
    permission_classes = [IsAuthenticated]    

    def post(self, request, *args, **kwargs):
        term = request.data.get("term")
        posts = Post.objects.filter(body__search=term)
        serializer = SearchSerializer(posts)
        breakpoint()
        return Response(serializer.data, status=HTTP_200_OK)

Here is the serializer:这是序列化程序:

class SearchSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = [
            'body'
        ]

Here is the post model:这是帖子 model:

class Post(models.Model):

    body = models.TextField("content", blank=True, null=True, max_length=5000)
    slug = AutoSlugField(populate_from=["category", "created_at"])
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="posts")
    published = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "post"
        verbose_name_plural = "posts"
        db_table = "posts"
        ordering = ["created_at"]
        get_latest_by = "created_at"

    def __str__(self):
        return self.body[0:30]

    def get_absolute_url(self):
        return self.slug

How am I then supposed to get the data in the front end?那我应该如何在前端获取数据呢?

UPDATE更新

If in the view the request object looks like this:如果在视图中请求 object 如下所示:

<rest_framework.request.Request: GET '/api/v1/posts/search/?term=looking'>

Then how do I get the term?那我怎么得到这个词呢? ('looking' at the moment) (此刻“看着”)

Because request.data gives me None因为 request.data 没有给我

kwargs is an empty dictionary kwargs 是一个空字典

So I changed the view and now it makes even less sense:所以我改变了观点,现在它变得更没有意义了:

class SearchPosts(APIView):
    permission_classes = [IsAuthenticated]    

    def get(self, request, *args, **kwargs):
        term = request.GET.get("term")
        posts = Post.objects.all().filter(body__search=term)
        breakpoint()
        serializer = SearchSerializer(posts)
        
        return Response(serializer.data, status=HTTP_200_OK)

Now I get an empty result if I do a print(posts).现在,如果我打印(帖子),我会得到一个空的结果。 The term is correct I checked that so why is body__search not working anymore?这个词是正确的我检查过为什么 body__search 不再工作了?

Changed it to a ListAPIView and I still get an empty data array in the response:将其更改为 ListAPIView,我仍然在响应中得到一个空数据数组:

# GENERIC VIEW TO GET POSTS FOUND BASED ON A SEARCH TERM
class SearchPosts(generics.ListAPIView):
    permission_classes = [IsAuthenticated]    
    serializer_class = SearchSerializer
    def get_queryset(self):
        term = self.request.GET.get("term")
        return Post.objects.filter(body__search=term)

If I remove the filter then all the posts data is in the response so why is body__search not working?如果我删除过滤器,那么所有帖子数据都在响应中,那么为什么 body__search 不起作用?

  def get(self, request, format=None):
        all_objects = Model.objects.all()
        serializer = YourSerializer(all_objects, many=True)
        return Response(serializer.data)

you missed to forgot get function please refer to the docs https://www.django-rest-framework.org/tutorial/3-class-based-views/您错过了忘记获取 function 请参阅文档https://www.django-rest-framework.org/tutorial/3-class-based-views/

You probably got AttributeError while trying to get serializer.data .您可能在尝试获取serializer.data时遇到了AttributeError You sent Queryset object to the serializer not single instance of Post model. If you want to serialize multiple objects just pass many parameter as True .您将Queryset发送给序列化程序,而不是Post model 的单个实例。如果要序列化多个对象,只需将many参数作为True传递。 From docs;来自文档;

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer.要序列化查询集或对象列表而不是单个 object 实例,您应该在实例化序列化程序时传递 many=True 标志。

So, change your usage like;所以,改变你的用法;

posts = Post.objects.filter(body__search=term)
serializer = SearchSerializer(posts, many=True)

try def get_serializer_class because in def post - serializer doesn't mean anything试试 def get_serializer_class 因为在 def post - serializer 没有任何意义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM