I have a filtered QuerySet which has a ManyToMany field 'Client'. I want to create a unique dict of all the Client objects in the query set so:
Projects Queryset: - Project1.client = <Client: 1> - Project2.client = <Client: 1> - Project3.client = <Client: 2> - Project4.client = <Client: 2> - Project5.client = <Client: 3> class Project(models.Model): client = models.ForeignKey(Client, blank=True, null=True)
I want to end up with a dict of client objects:
{<Client: 1>,<Client: 2>,<Client: 3>}
Some help would be appreciated :)
If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order. For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don't specify an order, you'll get some arbitrary row.
Project.objects.values('client').distinct()
Link to Django docs on queryset distinct() method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With