用Neo4J和Django!
django_neomodel的Python项目详细描述
开始
安装模块:
$ pip install django_neomodel
将以下设置添加到settings.py中::
NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:test@localhost:7687') # Make sure django_neomodel comes before your own apps INSTALLED_APPS = ( # django.contrib.auth etc 'django_neomodel', 'yourapp' )
在yourApp/models.py中编写第一个节点定义::
from neomodel import StructuredNode, StringProperty, DateProperty class Book(StructuredNode): title = StringProperty(unique_index=True) published = DateProperty()
为标签创建任何约束或索引。这需要在更改节点定义之后完成 非常类似于manage.py migrate
$ python manage.py install_labels
现在在一个视图中yourApp/views.py:
from .models import Book def get_books(request): return render('yourapp/books.html', request, {'books': Book.nodes.all()})
你已经准备好出发了。别忘了检查neomodel文档。
模型表格
将基类从structurednode切换到djangonode并添加一个“meta”类:
from datetime import datetime from django_neomodel import DjangoNode from neomodel import StructuredNode, StringProperty, DateTimeProperty, UniqueIdProperty class Book(DjangoNode): uid = UniqueIdProperty() title = StringProperty(unique_index=True) status = StringProperty(choices=( ('Available', 'A'), ('On loan', 'L'), ('Damaged', 'D'), ), default='Available') created = DateTimeProperty(default=datetime.utcnow) class Meta: app_label = 'library'
为djangonode创建一个模型表单类
class BookForm(ModelForm): class Meta: model = Book fields = ['title', 'status']
这个类现在可以像任何其他django表单一样使用。
设置
以下配置选项在django设置中可用(显示默认值)。 当django启动时,它们被映射到neomodel.config:
NEOMODEL_NEO4J_BOLT_URL = 'bolt://neo4j:neo4j@localhost:7687' NEOMODEL_SIGNALS = True NEOMODEL_FORCE_TIMEZONE = False NEOMODEL_ENCRYPTED_CONNECTION = True NEOMODEL_MAX_POOL_SIZE = 50
信号
信号与djangonode子类一起工作:
from django.db.models import signals from django_neomodel import DjangoNode from neomodel import StringProperty class Book(DjangoNode): title = StringProperty(unique_index=True) def your_signal_func(sender, instance, signal, created): pass signals.post_save.connect(your_signal_func, sender=Book)
支持以下操作:预保存,后保存,预删除,后删除。 在新创建的节点上,在post-savesignal参数中创建=true。
测试
您可以创建一个设置方法,在执行每个测试之前清除数据库:
from neomodel import db, clear_neo4j_database class YourTestClass(DjangoTestCase): def setUp(self): clear_neo4j_database(db) def test_something(self): pass
管理命令
已包含以下django管理命令。
安装标签
在节点定义的标签上设置约束和索引。这应该在任何架构更改后执行:
$ python manage.py install_labels Setting up labels and constraints... Found tests.someapp.models.Book + Creating unique constraint for title on label Book for class tests.someapp.models.Book Finished 1 class(es).
清除异物
删除数据库中的所有节点,警告没有确认!