gpt4 book ai didi

python - ViewSet 和附加检索 URL

转载 作者:行者123 更新时间:2023-12-04 12:04:48 26 4
gpt4 key购买 nike

我有一个 Django 模型 Donation我公开为一个 View 集。现在我想为第二个模型添加一个额外的 URL Shop其中 Donation 的相关实例可以通过参数 order_id 检索并且可以执行自定义操作。

# models.py
class Donation(models.Model):
id = models.AutoField(primary_key=True)
order_id = models.StringField(help_text='Only unique in combination with field `origin`')
origin = models.ForeignKey('Shop', on_delete=models.PROTECT)

class Shop(models.Model):
id = models.AutoField(primary_key=True)


# views.py
class DonationViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):

def retrieve(self, request, *args, **kwargs):
if kwargs['pk'].isdigit():
return super(DonationViewSet, self).retrieve(request, *args, **kwargs)
else:
shop_id = self.request.query_params.get('shop_id', None)
order_id = self.request.query_params.get('order_id', None)

if shop_id is not None and order_id is not None:
instance = Donations.objects.filter(origin=shop_id, order_id=order_id).first()
if instance is None:
return Response(status=status.HTTP_404_NOT_FOUND)

return Response(self.get_serializer(instance).data)

return Response(status=status.HTTP_404_NOT_FOUND)

@action(methods=['post'], detail=True)
def custom_action(self, request, *args, **kwargs):
pass

class ShopViewSet(viewsets.ModelViewSet):
pass

# urls.py
router = routers.DefaultRouter()

router.register(r'donations', DonationViewSet)
router.register(r'shops', ShopViewSet)
router.register(r'shops/(?P<shop_id>[0-9]+)/donations/(?P<order_id>[0-9]+)', DonationViewSet)
我的目标是让 http://localhost:8000/donations 指向整个 DonationViewSet。此外,我想通过 shop_id 的组合查找个人捐赠。和 order_id就像遵循 http://localhost:8000/shops/123/donations/1337/并且还执行像 http://localhost:8000/shops/123/donations/1337/custom_action/这样的自定义操作。我遇到的问题是第二个 url 返回整个查询集,而不仅仅是模型的单个实例。

最佳答案

您也可以使用 drf-nested-routers ,这将是这样的:

from rest_framework_nested import routers

from django.conf.urls import url

# urls.py
router = routers.SimpleRouter()
router.register(r'donations', DonationViewSet, basename='donations')
router.register(r'shops', ShopViewSet, basename='shops')

shop_donations_router = routers.NestedSimpleRouter(router, r'', lookup='shops')
shop_donations_router.register(
r'donations', ShopViewSet, basename='shop-donations'
)

# views.py
class ShopViewSet(viewsets.ModelViewSet):
def retrieve(self, request, pk=None, donations_pk=None):
# pk for shops, donations_pk for donations

@action(detail=True, methods=['PUT'])
def custom_action(self, request, pk=None, donations_pk=None):
# pk for shops, donations_pk for donations
这个没有测试!但除了你已经拥有的,这将支持:
donations/
donations/1337/
shops/123/donations/1337/
shops/123/donations/1337/custom_action

关于python - ViewSet 和附加检索 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67805564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com