update. 更新文章接口
This commit is contained in:
+35
-19
@@ -1,34 +1,50 @@
|
||||
from typing import List
|
||||
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router
|
||||
from ninja.pagination import paginate, PageNumberPagination
|
||||
|
||||
from article.models import Article
|
||||
from article.schema import ArticleSchema, ArticleCreateSchema
|
||||
from article.schema import ArticleUpdate, ArticleCreate, ArticleListOut, ArticleDetailOut
|
||||
|
||||
# Create your views here.
|
||||
|
||||
# Create your views here.
|
||||
router = Router(tags=['content'])
|
||||
router = Router(tags=['Article'])
|
||||
|
||||
|
||||
@router.get("/article", response=List[ArticleSchema], description="获取文章列表")
|
||||
@paginate(PageNumberPagination, page_size=50)
|
||||
def list_articles(request, ):
|
||||
# 安全校验 per_page(防止过大
|
||||
queryset = Article.objects.prefetch_related('attachments').select_related('author', 'section')
|
||||
return queryset
|
||||
@router.get("/article/", response=List[ArticleListOut], description="获取文章列表")
|
||||
@paginate(PageNumberPagination, page_size=20)
|
||||
def list_articles(request, title: str = '', section_id: int = 0):
|
||||
qs = (Article.objects.filter(title__contains=title).prefetch_related('attachments')
|
||||
.select_related('author', 'section').order_by("-id"))
|
||||
if section_id > 0:
|
||||
return qs.filter(section_id=section_id)
|
||||
return qs
|
||||
|
||||
|
||||
@router.post("/article", response=ArticleSchema)
|
||||
def create_article(request, payload: ArticleCreateSchema):
|
||||
# 注意:文件上传需额外处理(此处简化)
|
||||
article = Article.objects.create(
|
||||
title=payload.title,
|
||||
section_id=payload.section_id,
|
||||
author=request.auth, # 假设认证用户是作者
|
||||
content=payload.content,
|
||||
is_contribution=payload.is_contribution,
|
||||
is_published=payload.is_published,
|
||||
)
|
||||
@router.get("/article/{id}", response=ArticleDetailOut)
|
||||
def get_article(request, id: int):
|
||||
return get_object_or_404(Article.objects.prefetch_related("attachments"), id=id)
|
||||
|
||||
|
||||
@router.post("/article/", response=ArticleDetailOut)
|
||||
def create_article(request, data: ArticleCreate):
|
||||
article = Article.objects.create(**data.dict())
|
||||
return article
|
||||
|
||||
|
||||
@router.put("/article/{id}", response=ArticleDetailOut)
|
||||
def update_article(request, id: int, data: ArticleUpdate):
|
||||
article = get_object_or_404(Article, id=id)
|
||||
for attr, value in data.dict().items():
|
||||
setattr(article, attr, value)
|
||||
article.save()
|
||||
return article
|
||||
|
||||
|
||||
@router.delete("/article/{id}")
|
||||
def delete_article(request, id: int):
|
||||
article = get_object_or_404(Article, id=id)
|
||||
article.delete()
|
||||
return {"success": True}
|
||||
|
||||
Reference in New Issue
Block a user