05_Tutorial 5: Relationships & Hyperlinked APIs

1、关系和超链接

0、文档

https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/

https://q1mi.github.io/Django-REST-framework-documentation/tutorial/5-relationships-and-hyperlinked-apis_zh/

1、效果

05_Tutorial 5: Relationships & Hyperlinked APIs05_Tutorial 5: Relationships & Hyperlinked APIs

05_Tutorial 5: Relationships & Hyperlinked APIs05_Tutorial 5: Relationships & Hyperlinked APIs

 

2、name用法,配合reverse

第一,我们使用REST框架的reverse功能来返回完全限定的URL;

第二,URL模式是通过方便的名称来标识的,我们稍后将在snippets/urls.py中声明。

 

view

from rest_framework.reverse import reverse
urlpatterns = format_suffix_patterns([
    path('', views.api_root),       # 主index页面

    path('snippets/', views.SnippetList.as_view(), name='snippet-list'),        # name用法,配合reverse('snippet-list')
    path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'),
    path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'),

    path('users/', views.UserList.as_view(), name='user-list'),
    path('users/<int:pk>', views.UserDetail.as_view(), name='user-detail'),
])

 

 model

@api_view(['GET'])
def api_root(request, format=None):     # 入口,首页
    return Response({
        'users': reverse('user-list', request=request, format=format),      # reverse 反转
        'snippets': reverse('snippet-list', request=request, format=format),
    })

 

3、 超链接序列化:HyperlinkedModelSerializer

处理好实体之间的关系:希望在实体之间使用超链接方式

 

view视图不变

class UserList(generics.ListAPIView):  # user/ get方式
    queryset = User.objects.all().order_by('id')
    serializer_class = UserSerializer

序列化:继承HyperModelSerilizer

class UserSerializer(serializers.HyperlinkedModelSerializer):   # 实体之间使用超链接方式
    # snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())  # 添加一个显式字段 外键
    # 关联关系,alex的snippet的详情
    # many=True,多个字段,
    snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)

    class Meta:
        model = User
        fields = ['url', 'id', 'username', 'snippets']


class SnippetSerializer(serializers.ModelSerializer):

    owner = serializers.ReadOnlyField(source='owner.username')        # source参数控制哪个属性用于填充字段
    # # 它包含一个url字段  该snippet的highlight
    # 单个字段,继承与HyperlinkedRelatedField
    highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')

    class Meta:
        model = Snippet
        fields = ['url', 'id', 'title', 'code', 'linenos', 'language', 'style', 'owner', 'highlight']

 

4、HyperlinkedModelSerialize与ModelSerializer区别

HyperlinkedModelSerializerModelSerializer有以下区别:

  • 默认情况下不包括id字段。
  • 包含一个url字段,使用HyperlinkedIdentityField
  • 关联关系使用HyperlinkedRelatedField,而不是PrimaryKeyRelatedField

5、高亮代码

model层

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)  # 创建时间
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    # choices = [(1,'java'),(2,'python'),(3,''golang')]  # 下拉框选择,指代
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

    # Tutorial 4: Authentication & Permissions
    owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
    # 设置related_name参数来覆盖原名称owner_id(ORM查询时),实质,DB中还是owner_id
    highlighted = models.TextField()

    class Meta:
        ordering = ['created']

    # def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    def save(self, *args, **kwargs):
        """
        使用pygments库,创建一个高亮显示的HTML,表示代码段
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)  # 继承父类Model的save

 

6、HTML渲染器

一个HTML渲染器类,简单地返回预渲染的HTML
data = '<html><body>example</body></html>'
return Response(data)

view层

from rest_framework import renderers
class SnippetHighlight(generics.GenericAPIView):
    queryset = Snippet.objects.all()
    renderer_classes = [renderers.StaticHTMLRenderer]

    def get(self, request, *args, **kwargs):
        snippet = self.get_object()             # 视图显示的对象。
        return Response(snippet.highlighted)    # 某个字段

 

上一篇:win10系统下的DCOM配置


下一篇:OPC协议