通过slug过滤Django queryset

我也想用子弹过滤Post对象,应该如何处理呢? 该模型如下所示:

class Post(models.Model):
    slug = models.SlugField()
    title = models.CharField(max_length=100)
    post_json = models.CharField(max_length=100000, blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

看起来像这样

def load_post_json(request):
    obj = Post.objects.filter(author_id=request.user.id)
    data = list(obj.values())
    return JsonResponse({'posts': data})
评论
  • killo
    killo 回复

    You mean you want to filter by slug too?

    如果您将其作为查询参数提交,只需编写:

    def load_post_json(request):
    slug_name= request.data.get('slug_name')
    obj = Post.objects.filter(author_id=request.user.id, slug=slug_name)
    data = list(obj.values())
    return JsonResponse({'posts': data})
    

    If you want to extract it from the URL,capture it on urlpatterns in urls.py file:

       urlpatterns = [
        # …
        path('post/<slug_name:slug_name>/', load_post_json),
        # …
        ]
    

    then, get it as a function parameter in your load_post_json function:

       def load_post_json(request, slug_name):
         ...
    
  • laut
    laut 回复

    In the url you can capture the slug:

    # app/urls.py
    
    from django.urls import path
    from app.views import load_post_json
    
    urlpatterns = [
        # …
        path('post/<slug:slug>/', load_post_json, name='post_json'),
        # …
    ]

    然后在您的视图中,您可以过滤该段塞:

    # app/views.py
    
    from django.contrib.auth.decorators import login_required
    
    @login_required
    def load_post_json(request, slug):
        obj = Post.objects.filter(author_id=request.user.id, slug=slug)
        data = list(obj.values())
        return JsonResponse({'posts': data})

    That being said, it might be better to use the Django REST framework to define an API. This has tooling for serializers, etc. and thus makes it more convenient to define sets of views to obtain a list of items, create new ones, etc.

    Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].