从图形neo4j数据库中使用graphene-django和graphql检索关系属性

问题描述

我正在尝试创建一个简单的应用程序(使用django和python创建graphql api)。一切顺利,但我遇到了1个问题,我不知道该怎么做(我已经搜寻了几天,但我只是放弃了),所以我希望这里有人可以提供帮助(请参阅下文, )。

我正在将Django与graphene-django和neo4j用作(graph)数据库。我也使用中继模式。

使用graphql,我可以查询产品的所有属性,还可以查询关系(哪个产品属于哪个类别,反之亦然)。

现在,我的问题如下:在neo4j中,关系也有自己的属性,但是我不知道如何获取这些属性(例如,我想看看何时创建关系,这是关系上的属性)。

我目前有2种节点类型:类别和产品请参见下面的models(models.py):

class Category(Structurednode):    
    name = Stringproperty()
    shortname = Stringproperty()
    product = Relationship('Product','IN_CATEGORY')

class Product(Structurednode):
    name = Stringproperty()
    price = Stringproperty()
    description = Stringproperty()
    category = Relationship('Category','IN_CATEGORY')

下面是我使用的石墨烯-Django代码(schema.py):

class CategoryType(DjangoObjectType):   
    class Meta:
        model = Category
        neomodel_filter_fields = {
            'name': ['exact','icontains'],'shortname': ['exact'],}
        interfaces = (relay.Node,)

class ProductType(DjangoObjectType):
   
    class Meta:
        model = Product
        neomodel_filter_fields = {
            'name': ['exact','price': ['exact'],)

我在想的是,也许我可以尝试创建一个额外的字段并编写一个执行原始查询获取关系和属性的解析器(如下所示)

class ProductType(DjangoObjectType):
    relationship = graphene.String()
    
    class Meta:
        model = Product
        neomodel_filter_fields = {
            'name': ['exact',)
        
    def resolve_relationship(root,info,args):
        #perform the raw query here
    

现在要执行关系,我当然需要两个ID来进行如下查询: match(n:类别)-[r]->(x:Product)其中id(n)= 2358 AND id(x)= 187返回n,x,r 这样我就可以获得r的相关属性

我的问题是我无法获取连接节点的ID(仅root.id),有没有办法获取父ID?还是我的整体思维方式是错误的,并且有一个功能(我不了解,可能是石墨烯中的mayb?)可以用一种不同的方式(希望更好)来实现我想要的功能

感谢您的帮助。

解决方法

我没有在django中使用neo4j,但这应该可以工作:

class ProductType(DjangoObjectType):
   relationship = graphene.String()

   class Meta:
      model = Product
      neomodel_filter_fields = {
          'name': ['exact','icontains'],'price': ['exact'],}
      interfaces = (relay.Node,)
    
  def resolve_relationship(self,root,info,args):
      return self.id # or self.relationship.id or do any thing you want
         

Model Properties could also work 您需要添加relationship = graphene.String(source="<name-of-the-property>")