![](/img/trans.png)
[英]What is the correctly way to pass an orientdb @rid as a parameter, to DELETE request in django rest framework?
[英]What is the correctly way to delete edges with orientdb OGM in django rest framework?
我不知道如何使用 orientdb OGM 在 django rest 框架中創建一種刪除邊的方法。
我正在使用pyorient==1.5.5
和OrientDB 3.0.18
版本。
我有兩個頂點類: ousers
, ocompany
。 另外我有兩個關系(邊緣)類: ofriends
, oworksat
。 例如:
要建立ofriends
關系,我需要兩個ousers
。 為了建立oworksat
關系,我需要一個ouser
和一個ocompany
。 每個關系都有自己的集群 ID。
我知道我可以訪問這些功能:
(Pdb) dir(graph)
[ 'PROPERTY_TYPES', '_GROOVY_GET_DB', '_GROOVY_NULL_LISTENER', '_GROOVY_TRY', '類', 'delattr', '字典', '目錄', 'doc的', '當量', '格式', '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','客戶端'、'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_command_mapping'、'create_props_command_mapping'、 , 'delete_vertex' , 'delete_vertex_command' , 'drop', 'drop_all', 'drop_class', 'edge_from_record', 'edges_from_records', 'element_from_link', 'element_from_record', 'elements_from_cords_', 'elements_from_cords_from', 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' , '填充','property_from_schema','props_from_db','props_to_db','query','registry','save_element','scripts','server_version','strict','toposort_classes','valid_element_base','cordex_revertex' , 'vertexes_from_records']
如果我做:
graph.delete_vertex("#21:0")
它運行良好並刪除 #21:0 ouser
頂點行,它是ofriends
和oworskat
關系的一部分,因此,該命令還會刪除包含該頂點的關系。 顯然,我不想刪除整個頂點,只刪除特定的邊(不是類,只是關系行)。
我想知道是否存在像 delete_edge() 這樣的命令,但是 dir(graph) 沒有告訴我任何相關的東西。
設置.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()
模型.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)
序列化程序.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
根據pyorient OGM 文檔,從未添加該功能。 我已經在存儲庫中創建了一個問題。
所以目前,我使用 pyorient 客戶端通過原始查詢解決了我的問題:
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)。
自己構建命令的另一種方法是使用Graph.record_delete()
並將其傳遞給要刪除的邊的記錄 ID。
下面的代碼片段假設db
是OrientDB
一個實例,而rid
保存要刪除的鏈接的記錄ID:
cluster = rid[1:].split(':')[0]
record = rid[1:].split(':')[1]
db.record_delete(cluster, record)
作為側邊欄,我使用 OrientDB 的次數越多,我就越后悔選擇數據庫,因為它缺乏對功能不完整且現在也非常過時的 Python 驅動程序的支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.