Django REST:提供重复响应的get_queryset

2024-10-01 02:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的在线商店应用程序,所以当你想购买一个项目,一个按钮点击引导你到收费api。(例如,第2项将直接发送至/api/charge/2)

网址.py

from django.urls import path
from gallery.views import ClothingView
from gallery.api.views import ListClothes
from gallery.api.views import ChargeView

urlpatterns = [
    path('api/<int:num>/', ListClothes.as_view()),
    path('api/charge/<int:num>', ChargeView.as_view(), name='charge_api'),
]

视图.py

^{pr2}$

序列化程序.py

class ChargeSerializer(serializers.ModelSerializer):
    class Meta:
        model = ClothingModel
        fields = ('full_price', 'discount', 'description')

每次调用api时,我都会为Stripe(付款方式)创建一个charge对象,但这取决于服装项目id自我.kwargs在get_queryset()上链接到服装项目。当我在Stripe仪表板上单击一次后查看费用时,会同时收到多个费用(一次4次)。我已经硬编码了if self.count == 1:作为一种解决办法,但我知道这不是一个好的实践。在每个请求的get_queryset()中有多个调用是有原因的吗?我如何才能干净地实现?非常感谢。在


Tags: path项目frompyimportviewapias
2条回答
from django.conf import settings # new
from django.views.generic.base import TemplateView
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY

class HomePageView(TemplateView):
    template_name = 'stripe.html'

    def get_context_data(self, **kwargs): # new
        context = super().get_context_data(**kwargs)
        context['key'] = settings.STRIPE_PUBLISHABLE_KEY
        return context

def charge(request): # new
    if request.method == 'POST':
        charge = stripe.Charge.create(amount=5000,currency='ind',description='A Django charge',
            source=request.POST['stripeToken'])
        return render(request, 'charge.html')

只应在POST请求中创建对象。get_queryset在每次调用视图时都被调用(甚至对于GET请求)。因此,object create应该在view函数中移动。URL的动态部分可以从这里的view函数访问-https://docs.djangoproject.com/en/2.1/topics/http/urls/#example

class ChargeView(ListCreateAPIView):

    def post(self, request, num):
        charge = ClothingModel.objects.get(id=num)

相关问题 更多 >