Home > Net >  Trouble in querying deep nested related field in django serializer
Trouble in querying deep nested related field in django serializer

Time:11-26

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.

CodePudding user response:

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.

CodePudding user response:

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")
        )
  • Related