I'm new on Django and SQL and I'm trying to solve some simple problems to start to understand them.
I have 3 models: Client, Product and Order. I want to list the products ordered by a client.
The models:
class Client(models.Model):
name = models.CharField(max_length=32)
.....
class Product(models.Model):
product_name = models.CharField(max_length=32)
.....
class Order(models.Model):
client = models.ForeignKey(Client,on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
.....
My solution was:
client= Client.objects.get(id=1) # target client
orders = client.order_set.all()
# or alternatively orders = Order.objects.filter(client=client)
list_of_orders=[order.product for order in orders]
My question: is there a better solution that uses some features of Django to get the list, instead of the for loop?
CodePudding user response:
In your case, you can select only products from the queryset using values_list()
, you can add the values which you want to return for example:
products = Order.objects.filter(client=client).values_list('product__product_name', flat=True)
the example apove will return a list of product names.
You can read how it works here values_list in Django
CodePudding user response:
From a deeper search in the Django documentation, I found that the for loop is actually used to solve the case of my question.
To avoid a db query each loop iteration, Django provides the methods select_related() and prefetch_related().
Please see the two methods in this page