Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of Unique many-to-many records from a queryset

My models:

class Order(models.Model):
    ordered_by = models.ForeignKey(User)
    reasons = models.ManyToManyField(Reason)
class Reason(models.Model):
    description = models.CharField()

Basically a user creates an order and gives reasons for that order. ie, john has two orders (one for pencils because he is out AND because he doesn't like his current stock. a second order for pens because he is out).

I want to print a list out of all reasons a user has placed his orders. So under john, it should print "he is out", "he doesn't like his current stock"; those two lines only. If I simply select all of john's orders, iterate through them and print out their "reasons" it'll print "he is out", "he doesn't like his current stock" and then "he is out" again. I don't want these duplicate values.

How do I select a list of his reasons for ALL his orders so that the list has all unique rows?

like image 765
rsp Avatar asked Jun 09 '10 03:06

rsp


1 Answers

Reason.objects.filter(order__ordered_by=john).distinct()
like image 115
Zach Avatar answered Oct 09 '22 09:10

Zach