在Django Graphene中创建或更新多对多关系,可以通过以下步骤实现:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
groups = models.ManyToManyField('Group')
class Group(models.Model):
name = models.CharField(max_length=100)
DjangoObjectType
来创建类型,并在类型中定义多对多字段。import graphene
from graphene_django import DjangoObjectType
from .models import User, Group
class UserType(DjangoObjectType):
class Meta:
model = User
class GroupType(DjangoObjectType):
class Meta:
model = Group
class Query(graphene.ObjectType):
users = graphene.List(UserType)
groups = graphene.List(GroupType)
def resolve_users(self, info):
return User.objects.all()
def resolve_groups(self, info):
return Group.objects.all()
schema = graphene.Schema(query=Query)
class CreateUser(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
group_ids = graphene.List(graphene.Int, required=True)
user = graphene.Field(UserType)
def mutate(self, info, name, group_ids):
user = User.objects.create(name=name)
user.groups.set(group_ids)
user.save()
return CreateUser(user=user)
class UpdateUser(graphene.Mutation):
class Arguments:
user_id = graphene.Int(required=True)
group_ids = graphene.List(graphene.Int, required=True)
user = graphene.Field(UserType)
def mutate(self, info, user_id, group_ids):
user = User.objects.get(id=user_id)
user.groups.set(group_ids)
user.save()
return UpdateUser(user=user)
class Mutation(graphene.ObjectType):
create_user = CreateUser.Field()
update_user = UpdateUser.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
在上述代码中,CreateUser
和UpdateUser
是用于创建和更新多对多关系的两个解析器。mutate
方法中,我们首先创建或获取用户对象,然后使用set
方法来设置多对多关系。最后,保存用户对象并返回更新后的用户。
mutation
来调用解析器,并传递相应的参数。创建用户并设置多对多关系的示例mutation:
mutation {
createUser(name: "John", groupIds: [1, 2, 3]) {
user {
id
name
groups {
id
name
}
}
}
}
更新用户的多对多关系的示例mutation:
mutation {
updateUser(userId: 1, groupIds: [2, 3, 4]) {
user {
id
name
groups {
id
name
}
}
}
}
以上就是在Django Graphene中创建或更新多对多关系的完整步骤。在实际应用中,你可以根据具体需求进行相应的调整和扩展。对于更多关于Django Graphene的信息,你可以参考腾讯云的Django Graphene相关产品:Django Graphene。
领取专属 10元无门槛券
手把手带您无忧上云