为了账号安全,请及时绑定邮箱和手机立即绑定

基于 URL 输入的 Django 过滤查询集

基于 URL 输入的 Django 过滤查询集

达令说 2022-01-05 10:12:46
我正在尝试获取一个 API 端点api/v1/device-groups/?customer=<customer_uuid>,该端点返回与customer_uuidURL 中给定的相关的设备组,但我不确定如何创建它。models.pyclass Customer(models.Model):    customer_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)    customer_name = models.CharField(max_length=128, unique=True)class DeviceGroup(models.Model):    group_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)    customer_uuid = models.ForeignKey(Customer, on_delete=models.DO_NOTHING)    device_group_name = models.CharField(max_length=20)    color = models.CharField(max_length=8)    is_default = models.BooleanField(default=False)serializers.pyclass CustomerSerializer(serializers.HyperlinkedModelSerializer):    class Meta:        model = Customer        fields = ('customer_name', 'customer_uuid')class DeviceGroupSerializer(serializers.HyperlinkedModelSerializer):    customer = CustomerSerializer(many=False, read_only=True, source='customer_uuid')    class Meta:        model = DeviceGroup        fields = ('device_group_name', 'group_uuid', 'color', 'is_default', 'customer')我不知道我应该在我的views.py和urls.pyurls.pyrouter = routers.DefaultRouter()router.register(r'device-groups', views.DeviceGroupViewSet, base_name='device-groups')urlpatterns = [    url(r'api/v1/', include(router.urls)),]我根据 GET 请求views.py返回与此相关的所有设备组customer_uuid/api/v1/device-groups/?customer_uuid=0bc899e9-4864-4183-8bcd-06937c572143/class DeviceGroupViewSet(viewsets.ModelViewSet):    serializer_class = DeviceGroupSerializerqueryset = DeviceGroup.objects.filter(customer_uuid='0bc899e9-4864-4183-8bcd-06937c572143')我试图get_queryset像这样覆盖,但结果是KeyErrorviews.pyclass DeviceGroupViewSet(viewsets.ModelViewSet):    serializer_class = DeviceGroupSerializer    def get_queryset(self):        return DeviceGroup.objects.filter(customer_uuid=self.kwargs['customer_uuid'])我需要更改什么才能获得/api/v1/device-groups/?customer=<customer_uuid>/返回过滤设备组的 API 端点?
查看完整描述

1 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

?在 URL之后的任何内容都被视为查询参数列表:?customer=<uuid>意味着您将查询参数传递customer给您的请求。它们不是实际 URL 路径的一部分。

这些查询参数都是QueryDict request.GET由 Django添加到的。在 DRF 中,它们也可以被访问request.data



查看完整回答
反对 回复 2022-01-05
  • 1 回答
  • 0 关注
  • 134 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信