Django Filtering based on field values in

django, django-rest-framework, mongodb, python

Solution

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" 
}

Problem

I am using Django and I want to use filters in that My product and company Models are ``` class Product(models.Model): name = models.CharField(max_length=200) companyId = models.ForeignKey(Comapany) class Company(models.Model): domain = models.CharField(max_length=200) ``` I want to retrieve Products based on currently user's companyId. So I have implemented My view like this.. ``` class ListProducts(APIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser,) def get(self, request): if request.user.is_authenticated(): userCompanyId = request.user.get_profile().companyId products = Product.objects.filter(companyId__id__exact = userCompanyId) serializer = ProductSerializer(products) return Response(serializer.data) ``` My Product Data ``` { "_id": ObjectId("5284ceaae9cfff79368e1f29"), "companyId": "528458c4bbe7823947b6d2a3", "name": "Apple Juice" } { "_id": ObjectId("5267bb4ebbe78220588b4567"), "companyId": "52674f02bbe782d5528b4567", "name": "Small Soft & Moist Cranberry" } ``` My company Data ``` { "_id": ObjectId("528458c4bbe7823947b6d2a3"), "domain": "Manufacturing" } { "_id": ObjectId("52674f02bbe782d5528b4567"), "domain": "Manufacturing" } ``` I am getting output as `[]` The problem is that while studying filters from django doc I am not able to get it.. SO please help me..

Original source