Hey, I wonder about the solution to the question that is being posed mid video in the titular part of the ultimate django course. Basically, we have to select all products that are ordered, and sort them by name. To achieve that, Mosh does some pretty intricate mechanisms with selecting product IDs, then passing these IDs as a filter etc.
But I wonder, why can’t we just do:
query_set = OrderItem.objects.values(‘product__title’).distinct().order_by(“product__title”)
?
Not only does it work, but also it removes duplicates in the actual end result, whereas Mosh’s solution contains duplicates (6:02) in the vid. Am I missing something?
i think because the product isnot necessarily in an orderitem . so it will simply return ordered and distinct titles.
i came up with the following solution:
queryset = Product.objects.filter(id=F(‘orderitem__product_id’)).distinct().order_by(‘title’)
it does not throw any error. however, orderitem is not is the product_database. but in the course it was mentioned that django creates the reverse-relationship automatically, when we write in the OrderItem class:
product = models.ForeignKey(Product, on_delete=models.PROTECT)
so why does it work?
is the field oderitem in the product-class only added, when the product is added to an orderitem?
anybody knows?