ManytoMany与django Rest有关

时间:2018-06-08 08:09:14

标签: python django django-rest-framework manytomanyfield

modes.py

class Product(models.Model):
    product_name = models.CharField(max_length=32)
    quantity = models.IntegerField()
    remarks = models.TextField(blank=True)

class Vendor(models.Model):
    vendor_name = models.CharField(max_length=50)
    address = models.CharField(max_length=100)
    bill_no = models.CharField(max_length=8)
    product = models.ManyToManyField(Product)

serializers.py

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class VendorSerializer(serializers.ModelSerializer):
    product = ProductSerializer(many=True, read_only=False)
    class Meta:
        model = Vendor
        fields = '__all__'
    def create(self, validate_data):
        product_data = validate_data.pop('product')
        vendor = Vendor.objects.create(**validate_data)
        for product_data in product_data:
            Product.objects.create(vendor=vendor, **product_data)
        return Vendor

views.py

class VendorViewset(viewsets.ModelViewset):
      serializer_class = VendorSerializer
      queryset = Vendor.objects.all()

我应该如何编写产品视图,以便可以证明某些供应商的产品只能通过网址路由查看?

1 个答案:

答案 0 :(得分:1)

您可以使用@detail_route

from rest_framework.decorators import detail_route

class VendorViewset(viewsets.ModelViewset):
      serializer_class = VendorSerializer
      queryset = Vendor.objects.all()

    @detail_route(methods=['GET'])
    def products(request, pk=None):
        qs = self.get_object().product.all()
        serializer = ProductSerializer(qs, many=True)
        return Response(serializer.data)

然后供应商产品将由

提供
YOUCURRENT_PATH_TO_DETAIL_VENDOR/products