在Django中获取和发布

时间:2018-07-05 08:27:09

标签: python django rest django-rest-framework

我是Django rest框架的新手,我习惯于在.net中开发API 我想创建2个API,一个通过pk id 获取与之相关的文章和图片,一个通过 post 添加文章和照片的API,我尝试了不同的方法但是无法得到我想要的东西,如果有人可以帮助或分享一些我可以学到的东西的网站,那将是很好的,在此先感谢 PS:select_related仅给我文章模型的ID。

这些是我的2种型号:

from django.db import models


class Article(models.Model):
    Heading = models.CharField(max_length=200, null=True)
    Article = models.TextField(null=True)
    CreatedBy = models.IntegerField(null=True)
    CreatedDate = models.DateTimeField(null=True)
    IsDeleted = models.BooleanField(default=False)


class ArticleImage(models.Model):
    Image = models.ImageField(upload_to='photos/', null=True)
    ImageArticle = models.ForeignKey(Article, on_delete=models.CASCADE)

这些是我的序列化器:

from rest_framework import serializers
from .models import Article, ArticleImage


class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'Heading', 'Article')


class ArticleImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArticleImage
        fields = ('id', 'Image', 'ImageArticle')

这些是我的观点:

from django.shortcuts import render
from django.views import View
from rest_framework import views
from rest_framework import viewsets
from .models import Article, ArticleImage
from .serializers import ArticleSerializer, ArticleImageSerializer
from itertools import chain
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404


class ArticleView(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer


class ArticleImageView(viewsets.ModelViewSet):
    queryset = ArticleImage.objects.all()
    serializer_class = ArticleImageSerializer


class ArticleWImage(viewsets.ModelViewSet):
    queryset = ArticleImage.objects.all().select_related()
    serializer_class = ArticleImageSerializer


class ImageWArticle(viewsets.ModelViewSet):
    queryset = Article.objects.select_related()
    serializer_class = ArticleSerializer


class ArticleList(APIView):
    def get(self, request):
        article = Article.objects.all()
        article_image = ArticleImage.objects.all()
        return render(request, {
            'article': article,
            'articleImage': article_image
        })

URL:

from django.urls import path, include
from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register('articles', views.ArticleView)
router.register('articleImage', views.ArticleImageView)
router.register('articleWithImage', views.ArticleWImage)
router.register('imageWithArticle', views.ImageWArticle)


urlpatterns = [
    path('', include(router.urls)),
    path('articleImageGet/', views.ArticleList.as_view())
]

3 个答案:

答案 0 :(得分:0)

您可以使用Drango Rest Framework附带的通用视图。

对于您只需要GET和POST的用例,我认为CreateAPIView(用于POST),RetrieveAPIView(用于GET)就足够了。

http://www.django-rest-framework.org/api-guide/generic-views/#createapiview

http://www.django-rest-framework.org/api-guide/generic-views/#retrieveapiview

类似这样的东西:

private void Update(){
    this.transform.eulerAngles = CameraController.Instance.camTransform.eulerAngles;

    //Vector3 moveVector = Quaternion.Euler(this.transform.eulerAngles) * InputManager.MainJoystick ();

    // EDIT
    Vector3 moveVector = InputManager.MainJoystick ();
    moveVector = transform.TransformDirection(moveVector);

    moveVector.x = moveVector.x * walkingSpeed;
    moveVector.y = verticalVelocity;
    moveVector.z = moveVector.z * walkingSpeed;

    controller.Move (moveVector * Time.deltaTime);
}

答案 1 :(得分:0)

根据官方DRF docs(非常好),您可以尝试执行以下操作:

class FooList(APIView):
    def get(self, request, format=None):
        Foos = Foo.objects.all()
        serializer = FooSerializer(Foos, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = FooSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

然后,您必须在urls.py中将视图集正确注册为视图:

urlpatterns = [
    url(r'^foos/$', views.FooList.as_view()),
]

答案 2 :(得分:0)

您始终可以覆盖视图集的自然功能。学习如何覆盖的最佳方法是通过DRF codebase

例如一般说“ /文章” 将提供文章列表,而“ / articles / pk” 将提供该primary_key文章的文章信息。如果您想覆盖其他功能,可以执行以下操作...     从django.shortcuts导入get_object_or_404     从rest_framework.response导入响应     从.models导入Article,ArticleImage     从.serializers导入ArticleSerializer,ArticleImageSerializer

class ArticleViewSet(viewsets.ViewSet):
    """
    A simple ViewSet for listing or retrieving articles.
    """


    def retrieve(self, request, pk=None):
        queryset = Article.objects.all()
        article_instance = get_object_or_404(queryset, pk=pk)
        article_serializer = ArticleSerializer(article_instance)
        image_instance = ArticleImage.objects.get(ImageArticle=article_instance.id)

        return Response({
                'article': article_serializer.data, 
                 'image': image_instance.image
               })

如果您想进一步了解其工作原理,read this