Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: products() got multiple values for argument 'pk'

models.py

I have two models with manytomany field which makes me confuse everytime.

 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

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)

urls.py

from django.conf.urls import url, include
from . import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('vendor', views.VendorViewset)

urlpatterns = [
    url(r'', include(router.urls)),
]

Then I browse http://localhost:8000/vendor/1/products/ I get that error. How can this be solved?

like image 320
Ian Avatar asked Jun 08 '18 12:06

Ian


1 Answers

First argument of method should be self:

 @detail_route(methods=['GET'])
  def products(self, request, pk=None):
      qs = self.get_object().product.all()
      serializer = ProductSerializer(qs, many=True)
      return Response(serializer.data)
like image 101
neverwalkaloner Avatar answered Nov 01 '22 13:11

neverwalkaloner