Bas Jansen
Bas Jansen

Reputation: 3343

Querying a Neo4j DB using Django

I apologize before hand as the Django way of thinking is still very alien to me. I am trying to generate a very simple page that justs lists all results from a simple cypher query using Neo4j and Django (1.9.7) and I am using the Python Neo4j driver to access the database from Django. However, I am getting stuck and have reached the point where I am just blindly trying things, as such I would like some pointers/advice on how the basics of what I am trying to achieve should look.

models.py

from django.views.generic.listimport ListView
from neo4j.v1 import GraphDatabase, basic_auth
from django.db import models

# Connect to DB
driver=GraphDatabase.driver("foo1",auth=basic_auth("foo2","foo3"))
session=driver.session()

class Stuff(models.Model):
  query = "MATCH (t:Time) return t"
  results=session.run(query)
  # Sanity check -> This just shows that the database and query both work
  for foo in results:
    print foo
    break
  def __str__(self):
    return results

views.py

from django.views.generic.list import ListView
from .models import Stuff

# I assume that I should be using a ListView here (as I was trying to get a queryset or similar from my models).
class IndexView(ListView):
  template_name = 'index.html'

  def get_queryset(self):
    fooList = []
    for record in Stuff.objects.get():
      fooList.append(record)
    return fooList

index.html (not tested as I haven't managed to get this to 'show' yet)

{% block body %}

{% if fooList %}
  <h1>Woot!</h1>
{% endif %}

{% endblock %}

The above bits obviously don't work and complain about Stuff not having any objects, yet I am totally lost on how to continue (as I have been unable to find any good examples/documentation on using this driver inside Django).

Upvotes: 9

Views: 1307

Answers (2)

Patcho
Patcho

Reputation: 77

you can write a flat REsTFul API to communicate with a frontend maybe written in React Angular2 to dump and display your data. So first , you can use DRF(Django rest Framework), then everything would happen mostly in your views.py and serializers.py and a bit in your models.py. Why avoiding Django template, the query load might affect your app to run smoothly.

Upvotes: 0

hlihovac
hlihovac

Reputation: 478

Documentation of session object in neo4j python driver run method state that

run(statement, parameters=None, **kwparameters)

it returns StatementResult object as documented here

So according to the docs there is no objects property and therefore .objects.get() method does not exists.

Right way to do access records in returned StatementResult is shown in example as following:

for record in result:
      print("%s %s" % (record["title"], record["name"]))

So in your case you may want to do:

for record in Stuff:
  fooList.append(record)

Upvotes: 1

Related Questions