Django - Unique list from QuerySet

空扰寡人 提交于 2019-12-05 12:44:29

问题


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 :)


回答1:


Project.objects.values('client').distinct()

Link to Django docs on queryset distinct() method




回答2:


Just use distinct().



来源:https://stackoverflow.com/questions/5728283/django-unique-list-from-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!