使用下面的人爲的例子:使用graphene-django,可以定義兩個節點之間的循環關係嗎?
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的過濾器0.15.3,石墨烯的Django 1.2.0