當用戶訪問「的BaseURL /公司/ 6 /查詢/」,我知道COMPANY_ID是6Django的REST框架篩選查詢集基於URL
然後用戶就創建具有特定產品的查詢選項,但應該只看到屬於公司6
這裏的產品是我的視圖集:
class InquiryViewSet(viewsets.ModelViewSet):
queryset = Inquiry.objects.all()
serializer_class = InquirySerializer
def get_serializer(self, *args, **kwargs):
serializer_class = self.get_serializer_class()
context = self.get_serializer_context()
return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs)
這裏是我的串行:
class InquirySerializer(serializers.ModelSerializer):
def __init__(self, *args, company_id=None, **kwargs):
super(InquirySerializer, self).__init__(*args, **kwargs)
company_set = Company.objects.filter(pk=company_id)
self.fields['company'].queryset = company_set
company = serializers.HyperlinkedRelatedField(many=False,
view_name='company-detail',
queryset=Company.objects.all())
inquirer = UserPKField(many=False)
is_anonymous = serializers.BooleanField
product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__')
class Meta:
model = Inquiry
fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows')
read_only_fields = ('inquirer', 'inquiry_date')
而這裏的CompanyProductField
class CompanyProductField(serializers.PrimaryKeyRelatedField):
def __init__(self, *args, company_id=None, **kwargs):
super(CompanyProductField, self).__init__(*args, **kwargs)
self.company_id = company_id
def get_queryset(self):
product_query = Q(company__pk=self.company_id)
return Product.objects.filter(product_query)
必須有一個簡單的方法可以讓我訪問是已經在InquirySerializer的初始化方法,只是傳遞的COMPANY_ID,但我很爲難。
'self.root.company_id'就是我一直在尋找的! –