[Django]-Django Filtering based on field values in

5👍

I resolved the error. Actually The way of specifying how Product model’s companyId references Id field of company model was wrong. So I saw How userprofile references user model .I am mentioning here my changes.

Product Model

class Product(models.Model):
    name = models.CharField(max_length=200)
    company = models.ForeignKey(Company,null=True)

View

class ListProducts(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAdminUser,)
    model = Product

    def get(self, request):
        if request.user.is_authenticated():
            userCompanyId = request.user.get_profile().companyId
        products = Product.objects.filter(company = userCompanyId)
        serializer = ProductSerializer(products,many=True)
        return Response(serializer.data)

put company_id in Company data like this

{
   "_id": ObjectId("5284ceaae9cfff79368e1f29"),
   "company_id": "528458c4bbe7823947b6d2a3",
   "name": "Apple Juice" 
}
👤Pawan

0👍

Obviously your user profile model’s companyId is not an integer field, so you should adjust your Product model to have a compatible companyId type. Oh and yes: don’t you have a Company model ?

0👍

This line:

ProductSerializer(products)

Should be:

ProductSerializer(products, many=True)

Otherwise though your issue doesn’t seem to be related to Django REST framework, just to the particular filter you’re running not returning any results.

Double check that request.user.get_profile() is returning a correct profile, double check that userCompanyId is set correctly, and double check the number of results returned by Product.objects.filter(companyId__id__exact=userCompanyId).count().

I’d guess you either have userCompanyId set incorrectly, or there simply aren’t any matching Product records.

Leave a comment