Friday, March 1, 2013

Getting only the models related to my queryset.

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

--
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+unsubscribe@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.
 
 

No comments:

Post a Comment