Django根据URL输入过滤查询集

时间:2019-04-09 15:06:57

标签: python django django-rest-framework

我试图获取一个API端点class ANewFluterActivity : FlutterActivity() { override fun createFlutterView(context: Context): FlutterView { val matchParent = WindowManager.LayoutParams(-1, -1) val nativeView = this.createFlutterNativeView() val flutterView = FlutterView(this, null as AttributeSet?, nativeView) flutterView.setInitialRoute("YOUR_NEW_ROUTE") flutterView.layoutParams = matchParent this.setContentView(flutterView) return flutterView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GeneratedPluginRegistrant.registerWith(this) //THIS IS THE SECRET TO MAKE PLUGINS WORK PROPERLY } } ,该端点返回与URL中给定的api/v1/device-groups/?customer=<customer_uuid>相关的设备组,但不确定如何创建它。

customer_uuid

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)), ] ,在向views.py发出GET请求后,返回与此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

要获取返回过滤后的设备组的API端点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>/可以为我解决。

views.py

1 个答案:

答案 0 :(得分:1)

URL中?之后的所有内容均被视为查询参数列表:?customer=<uuid>表示您正在将查询参数customer传递给您的请求。它们不是实际URL路径的一部分。

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