1

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)

Poul3R
  • 45
  • 1
  • 5

2 Answers2

1

This should work

connectorData = ConnectorModel.objects.filter(userId=userId, productId__in=all_products)

for connector in connectorData:
    productListToDisplay.append(connector.product)
waranlogesh
  • 874
  • 9
  • 11
  • Unfortunately I can't append "connector.product" to array because ConnectorModel contain only productId as attribute. In addition, `allProducts = self.get_queryset()` return list of full objects, not only id so `productId__in=all_products` generate error. Do you have any other idea? And one more question. Is there any posibility to parse `product.id` and `connector.productId` to the same format to easy compare both? – Poul3R Dec 09 '18 at 21:09
  • 1
    I did it. Thanks mate!! I've just refactor your piece of code and now everything works nice. It's something between your and my solution :) – Poul3R Dec 09 '18 at 21:52
  • Sorry for the late reply. If I may add something, what's been done is not usually the preferred way to do it. This kind of things should be delegated to the database. Something like @Ken4scholares suggests is preferred. Doing something like the next should've been enough: `productListToDisplay = ConnectorModel.objects.filter(userId=userId, product__isnull=False)` – Willemoes Dec 10 '18 at 20:16
0

You could do this:

productListToDisplay = ConnectorModel.objects.filter(userId=userId, product__isnull=False).prefetch_related('product').values_list('product', flat=True)
Ken4scholars
  • 6,076
  • 2
  • 21
  • 38