graphene-django icon indicating copy to clipboard operation
graphene-django copied to clipboard

It doesn't seem possible to create circular connections in graphene-django

Open CaffeineFueled opened this issue 9 years ago • 5 comments

We'd like to take advantage of the networked nature of GraphQL queries to highly interconnect our data models, however, we've been unable to find a way to do this using graphene-django.

In the the JavaScript implementation, it seems to be possible for two nodes to define connections to each other (http://stackoverflow.com/questions/39256942/dynamically-creating-graphql-schema-with-circular-references#39290345), however, this doesn't seem possible in the Django implementation.

Here's a bit of sample code that demonstrates what we're trying to accomplish:

from django.db import models
from django_filters import FilterSet, OrderingFilter
from graphene import ObjectType, Schema, relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField


class Recipe(models.Model):
    name = models.CharField(max_length=50)
    ingredients = models.ManyToManyField('Ingredient', related_name='recipes')


class Ingredient(models.Model):
    name = models.CharField(max_length=50)


class RecipeFilter(FilterSet):

    order_by = OrderingFilter(fields=[('name', 'name')])

    class Meta:
        fields = {'name': ['icontains']}
        model = Recipe


class IngredientFilter(FilterSet):

    order_by = OrderingFilter(fields=[('name', 'name')])

    class Meta:
        fields = {'name': ['icontains']}
        model = Ingredient


class RecipeNode(DjangoObjectType):

    ingredients = DjangoFilterConnectionField(IngredientNode, filterset_class=IngredientFilter)

    class Meta:
        interfaces = [relay.Node]
        model = Recipe
        only_fields = ['name']


class IngredientNode(DjangoObjectType):

    recipes = DjangoFilterConnectionField(RecipeNode, filterset_class=RecipeFilter)

    class Meta:
        interfaces = [relay.Node]
        model = Ingredient
        only_fields = ['name']


class Queries(ObjectType):

    all_recipes = DjangoFilterConnectionField(RecipeNode, filterset_class=RecipeFilter)
    all_ingredients = DjangoFilterConnectionField(IngredientNode, filterset_class=IngredientFilter)


schema = Schema(query=Queries)

This implementation does not work since IngredientNode is not defined by the time it is referenced in RecipeNode.

Using a lambda to define the connection (recipes = DjangoFilterConnectionField(lambda: RecipeNode, filterset_class=RecipeFilter) ) results in an AttributeError: 'function' object has no attribute '_meta' error.

Attempting to assign the attribute after IngredientNode is defined (RecipeNode.ingredients = DjangoFilterConnectionField(IngredientNode, filterset_class=IngredientFilter)) raises no errors, but the ingredients attribute does not show up in the final schema.

A GraphQL query that demonstrates the type of questions we'd like to be able to answer:

{
  allRecipes(name_Icontains: "omelette") {
    edges {
      node {
        name
        ingredients(name_Icontains: "egg") {
          edges {
            node {
              name
            }
          }
        }
      }
    }
  }
  allIngredients(name_Icontains: "egg") {
    edges {
      node {
        name
        recipes(name_Icontains: "omelette") {
          edges {
            node {
              name
            }
          }
        }
      }
    }
  }
}

CaffeineFueled avatar Dec 28 '16 16:12 CaffeineFueled

A little more information: If we do away with DjangoFilterConnectionField and define our connections using only DjangoConnectionField, the lambda trick works.

from django.db import models
from graphene import ObjectType, Schema, relay
from graphene_django import DjangoObjectType, DjangoConnectionField


class Recipe(models.Model):
    name = models.CharField(max_length=50)
    ingredients = models.ManyToManyField('Ingredient', related_name='recipes')


class Ingredient(models.Model):
    name = models.CharField(max_length=50)


class RecipeNode(DjangoObjectType):

    ingredients = DjangoConnectionField(lambda: IngredientNode)

    class Meta:
        interfaces = [relay.Node]
        model = Recipe
        only_fields = ['name']


class IngredientNode(DjangoObjectType):

    recipes = DjangoConnectionField(RecipeNode)

    class Meta:
        interfaces = [relay.Node]
        model = Ingredient
        only_fields = ['name']


class Queries(ObjectType):

    all_recipes = DjangoConnectionField(RecipeNode)
    all_ingredients = DjangoConnectionField(IngredientNode)


schema = Schema(query=Queries)

Unfortunately, filtering is super important and we'd rather not roll our own.

CaffeineFueled avatar Dec 28 '16 23:12 CaffeineFueled

https://github.com/graphql-python/graphene-django/pull/58 I believe will resolve this should it land.

nickhudkins avatar Jan 19 '17 19:01 nickhudkins

This should be now fixed in master :) (please reopen if not)

syrusakbary avatar Mar 03 '17 02:03 syrusakbary

Now I'd like to put the filter inside a Where field, in order to be called like usersConnection(where:{email: "egg"})

So far I got

class UserWhereInput(FilterSet):
    class Meta:
        fields = ('email', )
        model = auth_models.User

class Query(graphene.ObjectType):
    users_connection = DjangoFilterConnectionField(User, filterset_class=UserWhereInput)

How can I make it use a Where field?

helpse avatar Oct 10 '18 21:10 helpse

2 days ago I came up with this question. Since then I've dug inside graphene_django.

class CustomDjangoFilterConnectionField(DjangoFilterConnectionField):
    """ Custom DjangoFilterConnectionField following OpenCrud specs """
    @property
    def args(self):
        filter_fields = dict(**self.filtering_args)
        ordering_field = filter_fields['order_by']
        del filter_fields['order_by']

        where = get_where_input_field(filter_fields, self.model)

        extra_args = {
            'where': where,
            'order_by': ordering_field,
        }

        return to_arguments(self._base_args or OrderedDict(), extra_args)

I've essentially created my own DjangoFilterConnectionField. Hope this helps somebody.

helpse avatar Oct 13 '18 06:10 helpse