Graphql Graphene Django创建多个实例

Graphql Graphene Django创建多个实例,graphql,graphene-django,Graphql,Graphene Django,假设我有一个models.py,有两个表: class Category(models.Model): cat = models.CharField(max_length=100) class Thing(models.Model): desc = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, b

假设我有一个models.py,有两个表:

class Category(models.Model):
    cat = models.CharField(max_length=100)


class Thing(models.Model):
    desc = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
我的模式如下:

class ThingType(DjangoObjectType):
    class Meta:
        model = Thing


class FindThing(graphene.ObjectType):
    things = graphene.List(
        ThingType,
        search=graphene.String(),
        thing=graphene.ID(),
    )

    def resolve_things(self, info, thing=None, search=None, **kwargs):
        qs = Thing.objects.all()

        if search:
            filter = (
                Q(desc__icontains=search)
            )
            qs = qs.filter(filter)
        if thing:
            qs = qs.filter(id=thing)

        return qs


class CreateThing(graphene.Mutation):
    id = graphene.Int()
    desc = graphene.String()
    category = graphene.Field(FindCategory)

    class Arguments:
        desc = graphene.String()
        category = graphene.Int()

    def mutate(self, info, desc, category):
        thing = Thing(
            desc=desc,
            category=Category.objects.get(id=category)
        )
        thing.save()

        return CreateThing(
            id=thing.id,
            desc=thing.desc,
            category=thing.category_id
        )
我已经设法创建了一个模式,其中可以创建一个新类别,该类别已经链接到新创建的单个内容:

mutation createCategory{
  createCategory(cat:"cat7", desc:"defg"){
    id
    cat
    desc
  }
}

是否可以创建CreateCography django graphene模式,在该模式中可以创建包含多个新事物的类别?

您可以允许CreateCography变体接受多个事物的描述列表:

CreateCategory:
    descs = graphene.List(String)

    class Arguments:
    descs = graphene.List(String)
然后在mutate函数中循环此列表:

new_things = []

for desc in descs:
    thing = Thing(
        desc=desc,
        category_id=category.id
    )
    thing.save()
    new_things.append(thing.desc)

return CreateCategory(
    id=category.id,
    cat=category.cat,
    descs=new_things
)

您可以允许CreateCography接受多个事物的描述列表:

CreateCategory:
    descs = graphene.List(String)

    class Arguments:
    descs = graphene.List(String)
然后在mutate函数中循环此列表:

new_things = []

for desc in descs:
    thing = Thing(
        desc=desc,
        category_id=category.id
    )
    thing.save()
    new_things.append(thing.desc)

return CreateCategory(
    id=category.id,
    cat=category.cat,
    descs=new_things
)