在Django Rest框架中使用OrientDB OGM删除边的正确方法是什么? [英] What is the correctly way to delete edges with orientdb OGM in django rest framework?

查看:76
本文介绍了在Django Rest框架中使用OrientDB OGM删除边的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使用orientdb OGM在django rest框架中创建删除边缘的方法.

I don't know how to create a method to delete edges in django rest framework, using orientdb OGM.

我正在使用 pyorient == 1.5.5 OrientDB 3.0.18 版本.

我有两个顶点类: ousers ocompany .我也有两个关系(边)类: ofriends oworksat .例如:

I have two vertex Classes: ousers, ocompany. Also I have two relationships (edges) Classes: ofriends, oworksat. So for example:

要建立 ofriends 关系,我需要两个 ousers .为了建立 oworksat 关系,我需要一个 ouser 和一个 ocompany .每个关系都有自己的群集ID.

To make a ofriends relationship, I need two ousers. And to make a oworksat relationship, I need one ouser and one ocompany. Every relationship has it own cluster id.

我知道我可以使用以下功能:

I know that I can access to these functions:

(Pdb) dir(graph)

['PROPERTY_TYPES','_GROOVY_GET_DB','_GROOVY_NULL_LISTENER','_GROOVY_TRY',' class ',' delattr ',' dict >","目录","文档"," eq ","格式"," ge ","获取属性"," gt ","哈希","初始化"',' le ',' lt ','模块',' ne ','new "," reduce "," reduce_ex "," repr "," setattr "," sizeof "," str ","子类挂钩","弱引用","_ last_cred","_last_db','_ last_user','batch','both','bothE','build_mapping','clear_registry','client','coerce_class_names','coerce_class_names_to_quoted','compute_all_properties','config','create_all',"create_class","create_edge","create_edge_command","create_function","create_props_mapping","create_vertex","create_vertex_command","delete_vertex" "delete_vertex_command" ,"drop","drop_all","drop_class","edge_from_record','edges_from_records','element_from_link','element_from_record','elements_from_links','elements_from_records','export','get_edge','get_element','get_vertex','gremlin','guard_reserved_words',','in_','include','init_broker_for_class','list_superclasses','ocompany''ofriends','open','ousers','out','outE','oworksat','populate','property_from_schema','props_from_db','props_to_db','query','registry','save_element',脚本","server_version","strict","toposort_classes","valid_element_base","vertex_from_record","vertexes_from_records"]

['PROPERTY_TYPES', '_GROOVY_GET_DB', '_GROOVY_NULL_LISTENER', '_GROOVY_TRY', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', '_last_cred', '_last_db', '_last_user', 'batch', 'both', 'bothE', 'build_mapping', 'clear_registry', 'client', 'coerce_class_names', 'coerce_class_names_to_quoted', 'compute_all_properties', 'config', 'create_all', 'create_class', 'create_edge', 'create_edge_command', 'create_function', 'create_props_mapping', 'create_vertex', 'create_vertex_command', 'delete_vertex', 'delete_vertex_command', 'drop', 'drop_all', 'drop_class', 'edge_from_record', 'edges_from_records', 'element_from_link', 'element_from_record', 'elements_from_links', 'elements_from_records', 'export', 'get_edge', 'get_element', 'get_vertex', 'gremlin', 'guard_reserved_words', 'inE', 'in_', 'include', 'init_broker_for_class', 'list_superclasses', 'ocompany', 'ofriends', 'open', 'ousers', 'out', 'outE', 'oworksat', 'populate', 'property_from_schema', 'props_from_db', 'props_to_db', 'query', 'registry', 'save_element', 'scripts', 'server_version', 'strict', 'toposort_classes', 'valid_element_base', 'vertex_from_record', 'vertexes_from_records']

如果我这样做:

graph.delete_vertex("#21:0")

它运作良好,并删除了#21:0上一个个顶点行,该行是 ofriends oworskat 关系的一部分,因此,命令删除包含该顶点的关系.显然,我不想删除整个顶点,而只删除特定的边(而不是类,而是关系行).

It works good and deletes #21:0 ouser vertex row, which is part of ofriends and oworskat relationships, so also, that command deletes the relationship where that vertex is included. Obviously, I don't want to delete the entire vertex, just only the specific edge (not the class, just the relationship row).

我想知道是否存在诸如delete_edge()之类的命令,但dir(graph)没有告诉我任何相关内容.

settings.py

settings.py

from pyorient.ogm import Graph, Config
from pyorient.serializations import OrientSerialization
from pyorient.ogm import declarative

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

config = RawConfigParser()
config.read(BASE_DIR + '/settings.ini')

ORIENTDB = {
    'NAME': config.get('orientdbConf', 'DB_NAME'),
    'USER': config.get('orientdbConf', 'DB_USER'),
    'PASSWORD': config.get('orientdbConf', 'DB_PASS'),
    'HOST': config.get('orientdbConf', 'DB_HOST'),
    'PORT': config.get('orientdbConf', 'DB_PORT'),
}

Config.from_url('plocal://'+ORIENTDB['HOST']+':'+str(ORIENTDB['PORT'])+'/'+ORIENTDB['NAME']+'',''+ORIENTDB['USER']+'', ''+ORIENTDB['PASSWORD']+'',initial_drop=False,serialization_type=OrientSerialization.Binary)
graph = Graph(Config.from_url(''+ORIENTDB['HOST']+'/'+ORIENTDB['NAME']+'',''+ORIENTDB['USER']+'', ''+ORIENTDB['PASSWORD']+'',initial_drop=False))
Node = declarative.declarative_node()
Relationship = declarative.declarative_relationship()

models.py

models.py

from core.settings import Node,Relationship,graph
from pyorient.ogm.property import (String, Date, DateTime, Decimal, Double,
    Integer, Boolean, EmbeddedMap, EmbeddedSet,Link, UUID)

class OUsers(Node):
    element_plural = 'ousers'
    postgresql_id=Integer(nullable=False,unique=True)

class OCompany(Node):
    element_plural = 'ocompany'
    postgresql_id=Integer(nullable=False,unique=True)

class OFriends(Relationship):
    label = 'ofriends'
    from_postgresql_ouser_id=Integer(nullable=False,unique=True)
    to_postgresql_ouser_id=Integer(nullable=False,unique=True)

class OWorksAt(Relationship):
    label = 'oworksat'
    from_postgresql_ouser_id=Integer(nullable=False,unique=True)
    to_postgresql_ocompany_id=Integer(nullable=False,unique=True)

graph.create_all(Node.registry)
graph.create_all(Relationship.registry)

serializers.py

serializers.py

from .models import (OUsers,OCompany,OFriends,OWorksAt)
from rest_framework import serializers
from django.contrib.auth import get_user_model
User = get_user_model()

class OFriendsSerializer(serializers.Serializer):
    from_postgresql_ouser_id = serializers.IntegerField()
    to_postgresql_ouser_id = serializers.IntegerField()

    def create(self, data):
        return OFriends.objects.create(**data)

    def update(self, instance, data):
        instance.from_postgresql_ouser_id = data.get("from_postgresql_ouser_id")
        instance.to_postgresql_ouser_id = data.get("to_postgresql_ouser_id")
        instance.save()
        return instance

class OFriendsSerializer(serializers.Serializer):
    from_postgresql_ouser_id = serializers.IntegerField()
    to_postgresql_ouser_id = serializers.IntegerField()

    def create(self, data):
        return OFriends.objects.create(**data)

    def update(self, instance, data):
        instance.from_postgresql_ouser_id = data.get("from_postgresql_ouser_id")
        instance.to_postgresql_ouser_id = data.get("to_postgresql_ouser_id")
        instance.save()
        return instance

api.py

class OFriendsViewSet(viewsets.ModelViewSet):

    def destroy(self, request, *args, **kwargs):
        queryset = graph.ofriends.query()
        import pdb;pdb.set_trace()
        # HERE should be the command 

推荐答案

根据问题.

According with the pyorient OGM documentation, that functionality was never added. I already created an issue in the repository.

因此,此刻,我使用pyorient客户端和原始查询解决了我的问题:

So at the moment, I solved my problem using pyorient client, with raw query:

pyorient_client.py

pyorient_client.py

from core.settings import ORIENTDB
import pyorient

def orientdbConnection():
    """Orientdb client connection"""
    client = None
    try:
        client = pyorient.OrientDB(ORIENTDB['HOST'], int(ORIENTDB['PORT']))
        session_id = client.connect( ORIENTDB['USER'], ORIENTDB['PASSWORD'] )
        if client.db_exists( ORIENTDB['NAME'], pyorient.STORAGE_TYPE_MEMORY ):
            client.db_open( ORIENTDB['NAME'], ORIENTDB['USER'], ORIENTDB['PASSWORD'])
    except Exception as e:
        print ("[ ERROR ] Fail orientdb connection. Error: " + str(e))
    return client

在api.py

from rest_framework import status
from rest_framework.response import Response
from core.pyorient_client import *

class OFriendsViewSet(viewsets.ModelViewSet):

    def destroy(self, request, *args, **kwargs):
        client = orientdbConnection()

        client.command("delete edge ofriends where @rid = '" + kwargs['pk'] + "'")

        return Response(status=status.HTTP_204_NO_CONTENT)

也许这对其他任何人都可能有用.请注意,我收到了o'friends @rid作为参数(通过在swagger UI中的DELETE方法中传递ID).

Maybe this could be useful for anyone else. Note that I receive o'friends @rid as a parameter (by passing the id in DELETE method in swagger UI).

这篇关于在Django Rest框架中使用OrientDB OGM删除边的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆