【问题标题】:REST API Django does not show all tables in different endpointsREST API Django 不显示不同端点中的所有表
【发布时间】:2022-01-15 15:19:44
【问题描述】:

我正在学习 REST API Django,希望您能耐心等待并帮助理解以下案例。

myproject/abcapp/forms.py

from django import forms
from .models import *

class ProfileForm(forms.ModelForm):
    class Meta:
        model=Profile
        fields = "__all__"
       
  
class Zoo_data_2020Form(forms.ModelForm):
    class Meta:
        model=Zoo_data_2020
        fields = "__all__"

myproject/abcapp/models.py

from django.conf import settings
from django.db import models


class ProfileQuerySet(models.QuerySet):
    pass

class ProfileManager(models.Manager):
    def get_queryset(self):
        return ProfileQuerySet(self.model,using=self._db)


class Profile(models.Model):
    name=models.CharField(settings.AUTH_USER_MODEL,max_length=200) 
    subtype=models.CharField(max_length=500)
    type=models.CharField(max_length=500)
    gender=models.CharField(max_length=500)
  
    objects = ProfileManager()

    class Meta:
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'

        managed = False
        db_table ='profiles'

    def __str__(self):
        return '{}'.format(self.name)
          
      
class Zoo_data_2020QuerySet(models.QuerySet):
    pass
  
class Zoo_data_2020Manager(models.Manager):
    def get_queryset(self):
        return Zoo_data_2020QuerySet(self.model,using=self._db)

class Zoo_data_2020(models.Model):
    name=models.CharField(max_length=200)
    size=models.DecimalField(decimal_places=3,max_digits=100000000)
    weight=models.DecimalField(decimal_places=3,max_digits=100000000)
    age=models.DecimalField(decimal_places=3,max_digits=100000000)
    
    objects = Zoo_data_2020Manager()

    class Meta:
        verbose_name = 'zoo_data_2020'
        verbose_name_plural = 'zoo_data_2020s'

        managed = False
        db_table ='zoo_data_2020'

    def __str__(self):
        return '{}'.format(self.name)

myproject/abcapp/api/views.py:

from rest_framework import generics, mixins, permissions
from rest_framework.views import APIView
from rest_framework.response import Response
import json
from django.shortcuts import get_object_or_404
from abcapp.models import *
from .serializers import *


def is_json(json_data):
    try:
        real_json = json.loads(json_data)
        is_valid = True
    except ValueError:
        is_valid = False
    return is_valid


class ProfileDetailAPIView(generics.RetrieveAPIView):
    
    permission_classes = []
    authentication_classes = []
    queryset= Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'id'


class ProfileAPIView(generics.ListAPIView):
    permission_classes = []
    authentication_classes= []
    serializer_class = ProfileSerializer

    passed_id = None
    search_fields = ('id','name','animal')
    queryset = Profile.objects.all()


    def get_queryset(self):
        qs = Profile.objects.all()
        query = self.request.GET.get('q')
        if query is not None:
            qs=qs.filter(name__icontains=query)
        return qs


  
class Zoo_data_2020DetailAPIView(generics.RetrieveAPIView):
    
    permission_classes = []
    authentication_classes = []
    queryset= Zoo_data_2020.objects.all()
    serializer_class = Zoo_data_2020Serializer
    lookup_field = ('id','name')
 

class Zoo_data_2020APIView(generics.ListAPIView):
    permission_classes =[]
    authentication_classes= []
    serializer_class = Zoo_data_2020Serializer

    passed_id = None
    search_fields = ('id','name')
    queryset = Zoo_data_2020.objects.all()


    def get_queryset(self):
        qs = Zoo_data_2020.objects.all()
        query = self.request.GET.get('q')
        if query is not None:
            qs=qs.filter(name__icontains=query)
        return qs

myproject/abcapp/api/serializers.py:

from rest_framework import serializers

from abcapp.models import *


class ProfileSerializer(serializers.ModelSerializer):
     class Meta:
        model=Profile
        fields = "__all__"
        
        read_only_fields = ['name']


class Zoo_data_2020Serializer(serializers.ModelSerializer):
     class Meta:
        model = Zoo_data_2020
        fields = "__all__"
        
        read_only_fields = ['name']

myproject/abcapp/api/urls.py:

from django.urls import path
from .views import *

urlpatterns = [
    path('', ProfileAPIView.as_view()),
    path('<id>/', ProfileDetailAPIView.as_view()),
    path('', Zoo_data_2020APIView.as_view()),
    path('<id>/', Zoo_data_2020DetailAPIView.as_view()),]

myproject/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/profile/', include('abcapp.api.urls')),
    path('api/zoodata2020/', include('abcapp.api.urls')),

]

所以当我调用 http://127.0.0.1:8000/api/profile/ 时,我会从表 Profile 中获取 数据,但是当我调用 http://127.0.0.1:8000/api/zoodata2020/ 时,我会再次从表 Profile 中获取 数据,而不是 Zoo_data_2020。但是当我从myproject/abcapp/api/urls.py中删除时:

path('', ProfileAPIView.as_view()),
path('<id>/', ProfileDetailAPIView.as_view()),

然后它向我显示表 Zoo_data_2020 中的数据,但我无法从表 Profile 中获取数据

如何解决?我确定我在应用程序和项目中的 urls.py 中都做错了。那么我需要做什么才能使端点分开?以及如何同时显示它们?

我想致电http://127.0.0.1:8000/api/profile/?search=TIGER 并因此向我提供来自表profiles 和zoo_data_2020 的信息,因为它们包含不同的数据,但“名称”大致相同,即TIGER。但是目前当例如我打电话给http://127.0.0.1:8000/api/profile/?search=TIGER时,它只显示来自表格Profile而不是来自Zoo_data_2020的数据

请帮助理解它以及如何解决它。提前致谢。

【问题讨论】:

    标签: python mysql django api rest


    【解决方案1】:

    在项目 urls.py 中,您不必多次引用同一个应用程序,您可以在应用程序的 urls.py 中这样做

    试试这个

    我的项目/urls.py:

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('api/', include('cfs.api.urls')),    
    ]
    

    myproject/abcapp/api/urls.py:

    urlpatterns = [
        path('profile', ProfileAPIView.as_view()),
        path('profile/<id>/', ProfileDetailAPIView.as_view()),
        path('zoo_data', Zoo_data_2020APIView.as_view()),
        path('zoo_data/<id>/', Zoo_data_2020DetailAPIView.as_view()),
    ]
    

    【讨论】:

    • 我按照你说的做了,然后运行127.0.0.1:8000/api/profile,但出现错误:请求方法:GET 请求 URL:127.0.0.1:8000/api/profile 使用 sbdata.urls 中定义的 URLconf,Django 尝试了这些 URL 模式,在这个order: admin/ api/ profile api/ profile// api/ zoodata2020 api/ zoodata2020// 当前路径 api/profile/ 与其中任何一个都不匹配。你看到这个错误是因为你的 Django 设置文件中有 DEBUG = True 。将其更改为 False,Django 将显示标准 404 页面。
    • 这个错误是在我尝试了你的方法后开始的,但它不起作用。所以我不会在上面修改我的答案,因为其他人可能想要改变我的初始状态。如果您知道如何解决,请在此处分享
    • 请编辑您的问题并添加完整的错误回溯,谢谢
    • 谢谢我修好了,你忘了在 path('profile', ProfileAPIView.as_view()) 中的 profile 后面加上“/”,在 zoodata2020 中也是如此。再次感谢您的帮助
    • 哦,我的错,很高兴知道你修好了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2017-01-16
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多