使用django-rest-framework我尝试实现一些简单的API。
以下是代码。
我面临的问题是:
我不确定我在做什么,因为这个问题正在发生。请帮帮我。
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)
URLS:
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()),
]
答案 0 :(得分:0)
你有没有理由不使用&#39; $&#39;表示路由中字符串的结尾?
除此之外,如果你打算做的是拥有一个列表视图,然后是每个带有ID的产品的单独视图,你应该重新访问Django Routers文档,因为你不需要两个路由语句实现这一目标。