使用以下人为的示例:
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)
如何定义和之间的循环关系RecipeNode
,IngredientNode
以便可以运行以下 GraphQL 查询:
{
allRecipes(name_Icontains: "gg") {
edges {
node {
name
ingredients(name_Icontains: "gg") {
edges {
node {
name
}
}
}
}
}
}
allIngredients(name_Icontains: "gg") {
edges {
node {
name
recipes(name_Icontains: "gg") {
edges {
node {
name
}
}
}
}
}
}
}
就目前而言,我无法参考IngredientNode
,RecipeNode
因为它尚未定义。如果我尝试使用我在其他地方看到的推荐的 lambda,我会收到AttributeError: 'function' object has no attribute '_meta'
.
class IngredientNode(DjangoObjectType):
recipes = DjangoFilterConnectionField(lambda: RecipeNode, filterset_class=RecipeFilter)
class Meta:
interfaces = [relay.Node]
model = Ingredient
only_fields = ['name']
如果我在事后尝试设置属性,我将无法ingredients
从配方中查询。没有错误,Graphiql 只是表现得好像ingredients
从未定义过。
class RecipeNode(DjangoObjectType):
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']
RecipeNode.ingredients = DjangoFilterConnectionField(IngredientNode, filterset_class=IngredientFilter)
我必须认为有一个我没有看到的简单解决方案。任何帮助,将不胜感激。谢谢!
Django 1.8.17,django-filter 0.15.3,graphene-django 1.2.0