On Fri, Mar 1, 2013 at 7:11 PM, Gabriel Koscky <dhe...@gmail.com> wrote: > Hi, I've been having some trouble with filtering the related models of a > queryset, > and I'm not sure if I'm approaching this wrong or if Django can't actually > do it. > > Basically I have some models with ManyToMany relationships, like: > > class User(models.Model): > name = models.CharField() > > class Product(models.Model): > name = models.CharField() > > class Order(models.Model): > user = models.ForeignKey(User) > > status = models.CharField() > > products = models.ManyToManyField(Product, through='OrderProduct') > > class OrderProduct(models.Model): > product = models.ForeignKey(Product) > order = models.ForeignKey(Order) > amount = models.IntegerField() > > > And I want to get all the products bought by User1, so I'd do something like > > Product.objects.filter(order__status='completed', order__user=User1) > > Which then returns just Product1, but now I want the amount the user bought, > > but it seems wrong to make another query like: > > Product1.orderproduct_set.filter(order__user=User1) > > And hit the database again to get data my first query can already bring > me... > > > So what I want to know is, based on a queryset that filters by related > models, > > is there a way to get just the actual related models of my result? > > > Thanks, > > Gabriel >
Hi Gabriel Read about select_related() and start from the appropriate point: https://docs.djangoproject.com/en/1.4/ref/models/querysets/#select-related Eg, this will result in only one query: qs = OrderProduct.objects.filter(order__user=user).select_related('product') for op in qs: print u'%d x %s' % (op.amount, op.product.name) Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users?hl=en. For more options, visit https://groups.google.com/groups/opt_out.