Luffy Xuecheng project - Course Modules

############### course modules ################

Course Module Requirements
 1 , return to the front of the list of all courses,
 2 , return to the front of course details of individual courses, 
which are both get request, if you want to achieve in a single class, you can inherit ViewSetMixin, 
and then on the url as_view dictionary supports passing parameters, and 
then covered and retrieve the list method method used to obtain all courses and obtaining individual course 

serialized attention point
 1 , the curriculum and course is one of the detail table, how to obtain one,
 two , how to become Chinese character choice
 3 , foreign key associations how reverse lookup,
 4 , get how-many, 

to understand these situations you know, so even if there are a thousand tables, this is also not running range, 
so you view, routing, serialization have a more profound understanding of,

 

############### Table Structure ################

from django.db Import Models 

class Course, (models.Model):
     "" " 
    curriculum 
    " "" 
    title = models.CharField (verbose_name = ' Course Name ' , max_length = 32 ) 
    course_img = models.CharField (verbose_name = ' Course Pictures ' , MAX_LENGTH = 64 ) 
    level_choices = ( 
        ( . 1, ' primary ' ), 
        ( 2, ' intermediate ' ), 
        ( 3, ' advanced '),
    ) 
    Level = models.IntegerField (= the verbose_name ' course the degree of difficulty ' , choices = level_choices, default =. 1 ) 

    DEF  __str__ (Self):
         return self.title 

class CourseDetail (models.Model):
     "" " 
    Course Details 
    " "" 
    Course, = models.OneToOneField (to = ' Course, ' ) 
    slogon = models.CharField (verbose_name = ' slogan ' , max_length = 255 ) 
    Why = models.CharField (verbose_name = ' Why should we learn? ' ,max_length=255)
    recommend_courses = models.ManyToManyField (verbose_name = ' recommended course ' , to = ' Course, ' , the related_name = ' rc ' ) 

    DEF  __str__ (Self):
         return  " Course Details: " + self.course.title 

class Chapter (models.Model) :
     "" " 
    chapters, sections and courses are one-to-one courses can have a lot of chapters, " 
    "" 
    NUM = models.IntegerField (verbose_name = ' section ' ) 
    name = models.CharField (verbose_name = ' section name ',max_length=32)
    course = models.ForeignKey(verbose_name='所属课程',to='Course')

    def __str__(self):
        return self.name

 

############### Serialization ################

from api import models

from rest_framework import serializers

class CourseSerializer(serializers.ModelSerializer):
    """
    课程序列化
    """
    level = serializers.CharField(source='get_level_display')
    class Meta:
        model = models.Course
        fields = ['id','title','course_img','level']


classCourseDetailSerializer (serializers.ModelSerializer):
     "" " 
    Course details serialization 
    " "" 
    # one2one / FK / Choice, across the table can be achieved using the source, 
    title = serializers.CharField (source = ' course.title ' ) 
    course_img = serializers .CharField (source = ' course.course_img ' ) 
    Level = serializers.CharField (source = ' course.get_level_display ' )
     # above is a custom field, behind which is a field source and a table which bind, 
    # so fields returned the following on the lot, 
    # this is the return data can be achieved across the table, 
    # get_level_display this one, can be achieved not just take a number, but the numbers represent characters, 
    #Note, some into the middle of the field, 


    # the M2M 
    Recommends = serializers.SerializerMethodField ()
     # SerializerMethodField, wrote this, you need to write a function in the following, 
    # This is to take the recommended curriculum Note: You can not use this many-source a, 
    chapter = serializers.SerializerMethodField ()
     # this is to take the section, 


    class Meta -: 
        Model = models.CourseDetail 
        Fields = [ ' Course ' , ' title ' , ' IMG ' , ' Level ' , ' slogon ' , 'Why ' , ' Recommends ' , ' Chapter ' ]
         # depth = 1, is to find two down, there will be many, and the multi corresponding data to get, but the data show too much, so we generally do not so used, 


    DEF get_recommends (Self, obj):   # obj is CourseDetail 
        # get all recommended courses 
        QuerySet = obj.recommend_courses.all () 

        return [{ ' the above mentioned id ' : row.id, ' title ' : row.title} for Row in QuerySet] 

    DEF get_chapter (Self, obj):
         # get all recommended courses
        = obj.course.chapter_set.all QuerySet ()   # This is a reverse lookup, 

        return [{ ' ID ' : row.id, ' name ' : row.name} for Row in QuerySet]

 

############### view ################

from rest_framework.views import APIView
from rest_framework.response import Response
from api import models
from rest_framework.viewsets import GenericViewSet,ViewSetMixin
from api.serializers.course import CourseSerializer,CourseDetailSerializer
from rest_framework.throttling import SimpleRateThrottle
from api.auth.auth import LuffyAuth


class CourseView(ViewSetMixin,APIView):

    def list(self,request,*args,**kwargs):
        """
        课程列表接口
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = {'code':1000,'data':None}

        try:
            queryset = models.Course.objects.all()
            ser = CourseSerializer(instance=queryset,many=True)
            ret['data'] = ser.data
            print(ret)
        except Exception as e:
            ret['code ' ] = 1001 
            RET [ ' error ' ] = ' Get course failed ' 

        return the Response (RET) 

    DEF Retrieve (Self, Request, * args, ** kwargs):
         "" " 
        Course Details Interface 
        : param Request: 
        : param args : 
        : param kwargs: 
        : return: 
        "" " 
        RET = { ' code ' : 1000, ' Data ' :} None 

        the try :
             # course 2 = ID 
            PK = kwargs.get ( 'pk') 

            # Course Details Object 
            obj = models.CourseDetail.objects.filter (COURSE_ID = PK) .first () 

            Ser = CourseDetailSerializer (= obj instance, MANY = False) 

            RET [ ' Data ' ] = ser.data 

        the except Exception AS E: 
            RET [ ' code ' ] = 1001 
            RET [ ' error ' ] = ' Get course failed ' 

        return the Response (RET)

 

############### routing ################

from django.conf.urls import url,include

from api.views import course
from api.views import account


urlpatterns = [
    # 方式一
    # url(r'^course/$', course.CourseView.as_view()),
    # url(r'^course/(?P<pk>\d+)/$', course.CourseView.as_view()),

    # 方式二
    url(r'^course/$', course.CourseView.as_view({'get':'list'})),
    url(r'^course/(?P<pk>\d+)/$', course.CourseView.as_view({'get':'retrieve'})),
]

 

############### Table Structure ################

 

############### Table Structure ################

Guess you like

Origin www.cnblogs.com/andy0816/p/12301990.html