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

我正在尝试获取一个 API 端点api/v1/device-groups/?customer=<customer_uuid>,该端点返回与customer_uuidURL 中给定的相关的设备组,但我不确定如何创建它。


models.py


class 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.py


class 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.py


urls.py


router = 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 = DeviceGroupSerializer


queryset = DeviceGroup.objects.filter(customer_uuid='0bc899e9-4864-4183-8bcd-06937c572143')

我试图get_queryset像这样覆盖,但结果是KeyError


views.py


class 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 端点?


达令说
浏览 135回答 1
1回答

慕标5832272

?在 URL之后的任何内容都被视为查询参数列表:?customer=<uuid>意味着您将查询参数传递customer给您的请求。它们不是实际 URL 路径的一部分。这些查询参数都是QueryDict&nbsp;request.GET由 Django添加到的。在 DRF 中,它们也可以被访问request.data。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python