0
使用django-rest-framework我試圖實現一些簡單的API。django-restframework detailview問題
以下是驗證碼。我對着
問題是:
- 的產品/(P \ d +)/從未執行ProductsDetailView。我始終獲得所有產品列表,而不考慮URL中的ID。
- 但是,當我從URL中刪除產品/時,我收到單一產品作爲響應。但是,不幸的是現在我不能擁有所有的產品,因爲該API的URL被刪除。
我不知道我正在做什麼錯,因爲這個問題正在發生。請幫幫我。
MODEL:
class Product(models.Model):
product_owner = models.ForeignKey(User, verbose_name='User')
product_imported_via = models.CharField(max_length=200, default="0", null=False, choices=PRODUCT_IMPORT_SOURCE,
verbose_name='Source of import')
product_title = models.CharField(max_length=100, null=False, verbose_name='Product title')
product_description = models.TextField(max_length=250, verbose_name='Product description')
product_qty = models.IntegerField(verbose_name='Quantity')
product_mrp = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Maximum retail price')
product_offer_price = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='Selling price')
_product_discount_amount = models.FloatField(null=True, editable=False, verbose_name='Discount amount',
db_column='product_discount_amount')
_product_discount_percentage = models.IntegerField(null=True, editable=False, verbose_name='Disount percentage',
db_column='product_discount_percentage')
product_sku = models.CharField(max_length=100, null=False, unique=True, verbose_name='SKU',help_text='Enter Product Stock Keeping Unit')
product_barcode = models.CharField(max_length=100, null=False, verbose_name='Barcode')
archive = models.BooleanField(default=False)
串行器:
from rest_framework import serializers
from .models import Product
class ProductsSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id','product_title', 'product_description', 'product_qty', 'product_mrp',
'product_offer_price','product_discount_amount','product_discount_percentage',
'product_sku','product_barcode')
瀏覽次數:
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Product
from .serializers import ProductsSerializer
from django.http import Http404
#Create your views here.
class ProductsListView(APIView):
def get(self, request):
print('In update list')
updates = Product.objects.all()
serializer = ProductsSerializer(updates, many=True)
return Response(serializer.data)
class ProductsDetailView(APIView):
def get_object(self, pk):
try:
return Product.objects.get(pk=pk)
except Product.DoesNotExist:
raise Http404
def get(self, request, pk):
update = self.get_object(pk)
serializer = ProductsSerializer(update)
return Response(serializer.data)
網址S:
from products.views import ProductsListView, ProductsDetailView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^products/', ProductsListView.as_view()),
url(r'^products/(?P<pk>\d+)/', ProductsDetailView.as_view()),
]
是的。在字符串的末尾添加'$'。我錯過了添加這些。 –