0

I've got a database with an simple Employee model and node in Django. I´m using Graphene to create an API around this that allows a user to retrieve the right data.

class Employee(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, )
    name = models.CharField(max_length=128)


class EmployeeNode(DjangoObjectType):
    class Meta:
        model = Employee
        fields = "__all__"
        interfaces = (graphene.relay.Node, )

Now in addition to this, I have a query that finds a "buddy" for every Employee, which is another Employee (ID) in the database, and a function (details irrelevant here) that finds the correct "buddy" in the database using some not further specified Django query.

class EmployeeNodeWithBuddy(DjangoObjectType):
    buddy_id = graphene.UUID()

    class Meta:
        model = Employee
        fields = "__all__"
        interfaces = (graphene.relay.Node, )

    @classmethod
    def get_queryset(cls, queryset, info):
        set_with_buddy_annotation = queryset.annotate(
            buddy_id=ExpressionWrapper(Subquery( 
                 ### Omitting the details of this query ###
              ).only('id')[:1], output_field=models.UUIDField()
            ), output_field=models.UUIDField())
        )
        return set_with_buddy_annotation

This works ok, but what I actually want is not the ID of the buddy, but the actual EmployeeNode. I can´t figure out if there is a good way to annotate/add info to this query to make it return the thing I want. It would look like:

class EmployeeNodeWithBuddy(DjangoObjectType):
    buddy_id = graphene.UUID()
    buddy = graphene.Field(EmployeeNode) # Field with EmployeeNode instead of just ID!

    class Meta:
        model = Employee
        fields = "__all__"
        interfaces = (graphene.relay.Node, )

    @classmethod
    def get_queryset(cls, queryset, info):
        set_with_buddy_annotation = queryset.annotate(
            buddy_id=ExpressionWrapper(Subquery( 
                 ### Omitting the details of this query ###
              ).only('id')[:1], output_field=models.UUIDField()
            ), output_field=models.UUIDField())
        )

        set_with_buddy_annotation = # Somehow fetch the EmployeeNode from the buddy_id  here?

        return set_with_buddy_annotation

Does this make sense to do and is this even possible?

Yellow
  • 3,955
  • 6
  • 45
  • 74

0 Answers0