drf hula hoop

Hula Hoop

Table 1.1 Design

  • Not often change values ​​in memory: choices form, to avoid cross-table low performance.

  • Sub-table: If the table columns are too many / a lot of content can choose the level of sub-table

  • Table autocorrelation

Models django.db Import from class the UserInfo (models.Model):    "" "User Table" ""    username = models.CharField (the verbose_name = 'username', MAX_LENGTH = 32)    password = models.CharField (the verbose_name = 'password ', 64-max_length =) class article This article was (models.Model):    "" "article list" ""    category_choices = (        (1,' advice '),        (2,' News'),        (3, 'share' ),        (4, 'Q'),        (5 'other')    )    category = models.IntegerField (= the verbose_name 'classification' choices = category_choices)    title = models.CharField (the verbose_name = 'title',= 32 MAX_LENGTH)    Image = models.CharField (= the verbose_name 'image path', max_length = 128) # / media / upload / ....



















  summary = models.CharField(verbose_name='简介',max_length=255)

  comment_count = models.IntegerField(verbose_name='评论数',default=0)
  read_count = models.IntegerField(verbose_name='浏览数',default=0)

  author = models.ForeignKey(verbose_name='作者',to='UserInfo')
  date = models.DateTimeField(verbose_name='创建时间',auto_now_add=True)

class ArticleDetail(models.Model):
  article = models.OneToOneField(verbose_name='文章表',to='Article')
  content = models.TextField(verbose_name='内容')


class Comment(models.Model):
  """ 评论表 """
  article = models.ForeignKey(verbose_name='文章',to='Article')
  content = models.TextField(verbose_name='评论')
  user = models.ForeignKey(verbose_name='评论者',to='UserInfo')
  # parent = models.ForeignKey(verbose_name='回复',to='self', null=True,blank=True)

1.2 System Architecture (CMS)

 

 

1.3 functions to achieve

1.3.1 New article (can not write)

Once to increase the data in the two tables:    DEF POST (Self, Request, * args, ** kwargs):        "" "new article (should manage development in the background)" ""        Ser = ArticleSerializer (the Data = request.data )        ser_detail = ArticleDetailSerializer (Data = request.data)        IF ser.is_valid () and ser_detail.is_valid ():            # increase articles            article_object = ser.save (= the author_id. 1)            ser_detail.save (= article This article was article_object)            return the Response ( 'Add success')        return the Response ( 'error')










1.3.2 Article list

1.3.3 Article Details

1.3.4 Comments list

  • View Comments List access time: http://127.0.0.1:8000/hg/comment/?article=2

  • add comment

    http://127.0.0.1:8000/hg/comment/

    {
    article:1,
    content:'xxx'
    }
    http://127.0.0.1:8000/hg/comment/?article=1

    {
    content:'xxx'
    }

2. Screening

Case: In the list of articles, we attach filtering capabilities.

All: http: //127.0.0.1: 8000 / hg / article / 
Filter: http: //127.0.0.1:? 8000 / hg / article / category = 2
class ArticleView(APIView):
  """ 文章视图类 """

  def get(self,request,*args,**kwargs):
      """ 获取文章列表 """
      pk = kwargs.get('pk')
      if not pk:
          condition = {}
          category = request.query_params.get('category')
          if category:
              condition['category'] = category
          queryset = models.Article.objects.filter(**condition).order_by('-date')
           
          pager = PageNumberPagination()
          result = pager.paginate_queryset(queryset,request,self)
          ser = ArticleListSerializer(instance=result,many=True)
          return Response(ser.data)
      article_object = models.Article.objects.filter(id=pk).first()
      ser = PageArticleSerializer(instance=article_object,many=False)
      return Response(ser.data)
drf components: built-in filtering function
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from . import models

from rest_framework.filters import BaseFilterBackend

class MyFilterBackend(BaseFilterBackend):

  def filter_queryset(self, request, queryset, view):
      val = request.query_params.get('cagetory')
      return queryset.filter(category_id=val)
   

class IndexView(APIView):

  def get(self,request,*args,**kwargs):
      # http://www.xx.com/cx/index/
      # models.News.objects.all()

      # http://www.xx.com/cx/index/?category=1
      # models.News.objects.filter(category=1)

      # http://www.xx.com/cx/index/?category=1
      # queryset = models.News.objects.all()
      # obj = MyFilterBackend()
      # result = obj.filter_queryset(request,queryset,self)
      # print(result)
       
      return Response('...')

3. view

  • APIView, the feeling did not provide functionality.

  • GenericAPIView, bridges, internally defined: get_queryset / get_serilizer / get_page ...

  • ListAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView,DestroyAPIView
class TagSer(serializers.ModelSerializer):
  class Meta:
      model = models.Tag
      fields = "__all__"

class TagView(ListAPIView,CreateAPIView):
  queryset = models.Tag.objects.all()
  serializer_class = TagSer

  def get_serializer_class(self):
      # self.request
      # self.args
      # self.kwargs
      if self.request.method == 'GET':
          return TagSer
      elif self.request.method == 'POST':
          return OtherTagSer
  def perform_create(self,serializer):
      serializer.save(author=1)

class TagDetailView(RetrieveAPIView,UpdateAPIView,DestroyAPIView):
  queryset = models.Tag.objects.all()
  serializer_class = TagSer

 

Achieve hula hoop

ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView 
+
custom hook Method

 

Guess you like

Origin www.cnblogs.com/YZL2333/p/11900694.html