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)
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
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)
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With