Search code examples
sqldjangodjango-viewsdjango-q

Django Queries using Q


I have the following

project model:

class Project(models.Model):
    creator = models.ForeignKeyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_lenght=200)
    co_workers = models.ManyToManyField(settings.AUTH_USER_MODEL)

table users:

id_user username
 1       Frank
 2       Steve
 3       Eddie

table projects:

id_project project_name id_creator
 1          project 1       1     
 2          project 2       1
 3          project 3       1
 4          project 4       1   

table projects_users(m2m) this table is for another workers for the same project:

id_user  id_project
 2         1
 3         1
 2         2
 3         2

when I make the following queries I get:

>>>Project.objects.filter(creator=1)

[project 1, project 2, project 3, project 4]

>>>Project.objects.filter(co_workers=1)

[]

And that's fine, but when I put:

>>>Project.objects.filter(Q(co_workers=1)| Q(creator=1))

[Project 1, Project 1, Project 2, Project 2, Project 3, Project 4]

I was expecting to get:

[project 1, project 2, project 3, project 4]

What am I doing wrong?


Solution

  • The reason you are getting Project 1 and Project 2 twice is because your or conditional still evaluates properly with either query. You need to use the distinct() method at the end of your queryset.

    Project.objects.filter(Q(co_workers=1)| Q(creator=1)).distinct()