英文:
How can I properly interact with many-to-many relationship in Django+GraphQL?
问题
我如何正确地在Django + GraphQL中处理多对多关系?
我有一个Game模型,它与User模型有多对多的关系。
class Game(models.Model):
name = models.CharField(max_length=256, blank=True)
users = models.ManyToManyField(to=User, blank=True, related_name='games')
class User(AbstractUser):
email = models.EmailField(max_length=128, verbose_name='email address', blank=False)
我需要将它连接到GraphQL,以便通过mutations读取和修改这些字段。
我已经有一个可以处理Game
的模式,但现在我也需要添加users
。
{
games {
edges {
node {
id
name
}
}
}
}
但是当我添加users
时,它不起作用,因为数据库中的Game
表没有users
字段。它有一个描述它们关系的games_game_users
表。
我应该如何修改我的代码以便能够使用game.users
字段?
英文:
How do I properly interact with many-to-many relationship in Django+GraphQL?
I have a Game model which has a many to many relationship to User model.
class Game(models.Model):
name = models.CharField(max_length=256, blank=True)
users = models.ManyToManyField(to=User, blank=True, related_name='games')
class User(AbstractUser):
email = models.EmailField(max_length=128, verbose_name='email address', blank=False)
I need to connect it to GraphQL so I can read and modify that fields via mutations.
I already have a schema to work with Game
without users
but now I need to add users as well
{
games {
edges {
node {
id
name
}
}
}
}
But it doesn't work when I add users
because the Game
table in db doesn't have a users
field. It has the games_game_users
table that describes their relationship.
How can I modify my code to be able to work with game.users
field?
答案1
得分: 0
如果您想在Django+GraphQL中与多对多关系进行交互,您应该正确定义您的节点。
这是我的情况下应该如何定义的方式:
class UserNode_(DjangoObjectType):
class Meta:
model = User
interfaces = (graphene.relay.Node,)
class GameNode(DjangoObjectType):
class Meta:
model = Game
interfaces = (graphene.relay.Node,)
users = graphene.List(UserNode_)
def resolve_users(value_obj, info):
return value_obj.users.all()
因此,这个GraphQL请求将显示您的游戏和连接的用户:
{
games {
edges {
node {
id
title
users {
id
username
email
}
}
}
}
}
要向游戏中添加或删除用户,请使用add()
和remove()
方法:
game.users.add(new_user)
game.users.remove(old_user)
英文:
If you want to interact with many-to-many relationship in Django+GraphQL you should define your Nodes correctly.
That's how it should be defined for my case:
class UserNode_(DjangoObjectType):
class Meta:
model = User
interfaces = (graphene.relay.Node,)
class GameNode(DjangoObjectType):
class Meta:
model = Game
interfaces = (graphene.relay.Node,)
users = graphene.List(UserNode_)
def resolve_users(value_obj, info):
return value_obj.users.all()
So this GraphQL request will display your games and connected users
{
games {
edges {
node {
id
title
users {
id
username
email
}
}
}
}
}
To add or to remove users from the game use add()
and remove()
methods:
game.users.add(new_user)
game.users.remove(old_user)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论