Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-rest-viewsets

Comparing instance of different models - Django REST Framework


I'am just looking for answer for my (seems to be stupid) question. I've already watched few stackoverflow posts but any of them was helpful :(

My question is how to compare two instance of different models with different?

Here is my case:

I've got two models: Product and Connector. First include id(pk), name, ect. Another include id(pk), productId(fk), userId(fk), ect.

My goal is to prepare view that list only product which are in Connector db-table as product(fk).

def list(self, request, *args, **kwargs):
    # return only product user's watching
    userId = self.request.user.id
    connectorData = ConnectorModel.objects.filter(userId=userId)
    allProducts = self.get_queryset()
    productListToDisplay = []

    for product in allProducts:
        for connector in connectorData:
            if product.id == connector.productId:
                # HERE IS A PROBLEM 
                productListToDisplay.append(product)

    serializer = ProductSerializer(productListToDisplay, many=True)
    return Response(serializer.data)

Problem is that Django consider "product.id" and "connector.productId" as totally different types. Firs is "core.models.ProductModel" and second is "core.models.ConnectorModel". I was trying to parse it using int() but it generate errors.

How I can compare this two values to add object to productListToDisplay array?

(I saw django doc - Comparing objects but there is no helpful information for this case)


Solution

  • This should work

    connectorData = ConnectorModel.objects.filter(userId=userId, productId__in=all_products)
    
    for connector in connectorData:
        productListToDisplay.append(connector.product)