mogui / pyorient

Orientdb driver for python that uses the binary protocol.
Apache License 2.0
167 stars 126 forks source link

How to get the last record in a query? #285

Open LegolasVzla opened 5 years ago

LegolasVzla commented 5 years ago

I don't know how to get the last record of an edge in django rest framework, using orientdb OGM.

I'm using pyorient==1.5.5 and OrientDB 3.0.18 version.

I have a relationship (edge) called OFriends and this is what I've tried:

queryset = graph.ofriends.query()

(Pdb) dir(graph) ['WhatFunction', 'WhatFunctions', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'gt', 'hash', 'init', 'iter', 'le', 'len', 'lt', 'module', 'ne', 'new', 'reduce', '__reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref__', '_class_props', '_graph', '_params', '_subquery', 'all', 'append_what_function', 'arithmetic_string', 'build_optional_clauses', 'build_props', 'build_select', 'build_what', 'build_wheres', 'count', 'filter', 'filter_by', 'filter_string', 'first', 'group_by', 'let', 'limit', 'lock', 'one', 'order_by', 'parse_prop_name', 'parse_record_prop', 'prepare', 'rid_lower', 'sanitise_prop_name', 'scalar', 'skip', 'slice', 'source_name', 'sub', 'unique_prop_name', 'unwind', 'what', 'what_args']

I thought that using limit() as below:

queryset = graph.ofriends.query().limit(1)

Will retrieve me the last record, but it still is a query: <class 'pyorient.ogm.query.Query'>

And iterating it:

(Pdb) [print(i.aux_id) for i in queryset]
10
12
100
[None, None, None]

It retrieve me all the values and not the last one. I tried also using order_by() but I get this error:

queryset = graph.ofriends.query().order_by('aux_id')
(Pdb) [print(i.aux_id) for i in queryset]
*** AttributeError: 'str' object has no attribute 'context_name'

So, Is it possible to get the last aux_id by using order_by? How?...

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')

DATABASES = {
    'default': {
        'ENGINE': config.get('postgresdbConf', 'DB_ENGINE'),
        'NAME': config.get('postgresdbConf', 'DB_NAME'),
        'USER': config.get('postgresdbConf', 'DB_USER'),
        'PASSWORD': config.get('postgresdbConf', 'DB_PASS'),
        'HOST': config.get('postgresdbConf', 'DB_HOST'),
        'PORT': config.get('postgresdbConf', 'DB_PORT'),
    },
    '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://'+DATABASES['orientdb']['HOST']+':'+str(DATABASES['orientdb']['PORT'])+'/'+DATABASES['orientdb']['NAME']+'',''+DATABASES['orientdb']['USER']+'', ''+DATABASES['orientdb']['PASSWORD']+'',initial_drop=False,serialization_type=OrientSerialization.Binary)
graph = Graph(Config.from_url(''+DATABASES['orientdb']['HOST']+'/'+DATABASES['orientdb']['NAME']+'',''+DATABASES['orientdb']['USER']+'', ''+DATABASES['orientdb']['PASSWORD']+'',initial_drop=False))
Node = declarative.declarative_node()
Relationship = declarative.declarative_relationship()

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 OFriends(Relationship):
    label = 'ofriends'
    aux_id=Integer(nullable=False,unique=True)
    from_postgresql_ouser_id=Integer(nullable=False,unique=True)
    to_postgresql_ouser_id=Integer(nullable=False,unique=True)

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

serializers.py

from .models import (OFriends)
from rest_framework import serializers

class OFriendsSerializer(serializers.Serializer):
    aux_id = serializers.IntegerField()
    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.aux_id = data.get("aux_id")
        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 create(self,request):
        aux_id = ''
        queryset = graph.ofriends.query()
        # HERE is where I want to get the last aux_id
nikulukani commented 4 years ago

Try graph.ofriends.query().order_by(OFriends.aux_id, reverse=True).limit(1).first().aux_id