Django.fun

Trouble in querying deep nested related field in django serializer

I have models this deep nested related model that looks like this:

class User(models.Model):
  username = models.Charfield(max_length=20)
  ...
class Workspace(models.Model):
  ...

class Folder(models.Model):
  workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE)

class File(models.Model):
  folder = models.ForeignKey(Folder, on_delete=models.CASCADE)

class Member(models.Model):
  user = models.ForeignKey(User,  on_delete=models.CASCADE)
  workspace = models.ForeignKey(Workspace, related_name="members", on_delete=models.CASCADE)


class Post(models.Model):
  file = models.ForeignKey(File, on_delete=models.CASCADE)

Now my question is how can I have a Post query result that looks like this:

{
  "id": 1,
  "file" 2,
  "members" : [1,2,3]
}


I tried using SlugRelatedField in the serializer but I can seem to get it right.

Answers: 2

Answered by Mohamad Bastin, Nov. 25, 2021, 1:01 p.m.

You can add a property method to your Post model.
something like this:

@property
def users(self):
    return self.file.folder.workspace.members

And add 'users' field to your Post serializer like a normal field.

Answered by Jonathan Aplacador, Nov. 26, 2021, 3:35 a.m.

I came up with an answer although I don't know if this is the optimal solution but I use SerializerMethod field.

authors = serializers.SerializerMethodField()

    def get_authors(self, obj):
        print(self)
        print(obj)
        workspace = obj.file.folder.workspace.id
        return Member.objects.filter(workspace=workspace).values(
            uid=F("user__id"), first_name=F("user__first_name"), last_name=F("user__last_name")
        )