Jessica Chambers
Jessica Chambers

Reputation: 1316

Django: filter returns empty result

I have the following table in my PostGreSQL database :

          workspace_role_id           | workspace_role_name 
--------------------------------------+---------------------
 3f76103f-732a-435a-a88f-737f4a6f1b87 | Owner
 c73b7c35-237e-4e13-8269-b259c2858b71 | Admin
 a61890fc-1c29-4817-8687-30786a5db17a | User

built from this Django model:

class WorkspaceRole(models.Model):
    class Meta:
        ordering = ("workspace_role_name",)

    workspace_role_id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False)
    workspace_role_name = models.CharField(max_length=64, unique=True)

    def __repr__(self):
        return f"<{self.__class__.__name__}: {self.workspace_role_name}>"

And I want to retrieve the workspace_role_name from the ID.

However, the result of

WorkspaceRole.objects.filter(workspace_role_id="a61890fc-1c29-4817-8687-30786a5db17a")

is an empty queryset <QuerySet []>, but when I run

WorkspaceRole.objects.all()

I get the correct output: <QuerySet [<WorkspaceRole: Admin>, <WorkspaceRole: Owner>, <WorkspaceRole: User>]>

What am I doing wrong with my filter?

Upvotes: 0

Views: 3352

Answers (3)

Boda
Boda

Reputation: 419

I know this an old thread, but this is quite high in search results and I found the early seeds for the solution in this answers.

Simply put, this usually indicates a mis-match in types between the data in the db and the filters one is using. In my case for example I was using array of text instead of just text. Same as the answer above, where it was using a text for filtering a uuid field. So keep that in mind.

Upvotes: 0

Jessica Chambers
Jessica Chambers

Reputation: 1316

After some tinkering with a colleague, the solution was to use:

with in_database(my_db, write=True):
    id = uuid.UUID('a61890fc-1c29-4817-8687-30786a5db17a')
    WorkspaceRole.objects.filter(workspace_role_id=id)

Upvotes: 0

Lu Chinke
Lu Chinke

Reputation: 683

Upgrade your searching...

import uuid
id = uuid.UUID('a61890fc-1c29-4817-8687-30786a5db17a')
WorkspaceRole.objects.filter(workspace_role_id=id)

Upvotes: 1

Related Questions