django-neomodel

repository·master·Indexed 43 days ago

https://github.com/neo4j-contrib/django-neomodel

A bridge that allows developers to use Neo4j graph databases within a Django application using the neomodel OGM. It provides DjangoNode for integration with Model Forms, Signals, and the Django admin, as well as management commands like install_labels for constraints and indexes. Requires Python 3.8+ and Neo4j 5.x or 4.4 (LTS).

Tokens
2.6K
Snippets
12
Records
16
Agent score
55%

What's inside django-neomodel

  1. Test Django-Neomodel applications

    master

    To ensure a clean state during testing, use clear_neo4j_database from neomodel in your test class's setUp method.

    from neomodel import db, clear_neo4j_database
    from django.test import TestCase
    
    class YourTestClass(TestCase):
        def setUp(self):
            clear_neo4j_database(db)
    
        def test_something(self):
            pass
  2. Install and configure django-neomodel

    master

    To use Neo4j with Django, install the django_neomodel package and add it to your INSTALLED_APPS.

    Important: django_neomodel must appear before your own application apps in the INSTALLED_APPS list. If you use django.contrib.auth, ensure django_neomodel is placed before it or your custom apps.

    Requirements:

    • Python 3.8+
    • Neo4j 5.x or 4.4 (LTS)
    $ pip install django_neomodel
    # settings.py
    import os
    
    NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:foobarbaz@localhost:7687')
    
    INSTALLED_APPS = (
        'django_neomodel',
        'yourapp'
    )
  3. Configure django-neomodel settings

    master

    The following settings are available in your Django configuration. These are mapped to neomodel.config during startup:

    • NEOMODEL_NEO4J_BOLT_URL: The connection URL for Neo4j (default: 'bolt://neo4j:neo4j@localhost:7687').
    • NEOMODEL_SIGNALS: Enables or disables Django signals (default: True).
    • NEOMODEL_FORCE_TIMEZONE: Boolean to force timezone settings (default: False).
    • NEOMODEL_MAX_CONNECTION_POOL_SIZE: Maximum size of the connection pool (default: 50).
  4. Use DjangoModelForm with DjangoNode

    master

    Once a model inherits from DjangoNode, it can be used with standard Django ModelForm classes just like a regular Django ORM model.

    from django import forms
    from .models import Book
    
    class BookForm(forms.ModelForm):
        class Meta:
            model = Book
            fields = ['title', 'status']
  5. Use Django signals with DjangoNode

    master

    Signals work with DjangoNode subclasses. You can connect to standard Django signals like pre_save, post_save, pre_delete, and post_delete.

    In the post_save signal, the created argument will be True if the node was freshly created.

    from django.db.models import signals
    from django_neomodel import DjangoNode
    from neomodel import StringProperty
    
    class Book(DjangoNode):
        title = StringProperty(unique_index=True)
        class Meta:
            app_label = 'library'
    
    def your_signal_func(sender, instance, signal, created):
        pass
    
    signals.post_save.connect(your_signal_func, sender=Book)
  6. Define Neo4j nodes with DjangoNode

    master

    While you can use standard neomodel.StructuredNode, you should use django_neomodel.DjangoNode if you want to use Django features like Model Forms and Signals.

    When using DjangoNode, you must include a Meta class with an app_label to integrate with Django's app registry.

    from datetime import datetime
    from django_neomodel import DjangoNode
    from neomodel import 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'
  7. Configure Neomodel settings via Django settings

    master

    Django Neomodel allows you to configure the underlying neomodel settings directly through your Django settings.py file. The following Django settings are supported and will override the default neomodel configuration:

    • NEOMODEL_NEO4J_BOLT_URL: Sets the Neo4j Bolt URL (maps to neomodel.config.DATABASE_URL).
    • NEOMODEL_FORCE_TIMEZONE: A boolean that determines if timezones should be forced (maps to neomodel.config.FORCE_TIMEZONE).
    • NEOMODEL_MAX_CONNECTION_POOL_SIZE: Sets the maximum size of the connection pool (maps to neomodel.config.MAX_CONNECTION_POOL_SIZE).
  8. Register Neomodel classes with the Django admin

    master

    To make your Neomodel classes visible and editable in the Django admin interface, use the register function provided by django_neomodel.admin. This function acts as a wrapper around the standard django.contrib.admin.site.register method, specifically designed to handle Neomodel classes.

    Usage:

    1. Define your ModelAdmin class (inheriting from admin.ModelAdmin).
    2. Call register(YourNeomodelClass, YourModelAdminClass).
    from django_neomodel.admin import register
    from .models import MyNeomodel
    from django.contrib import admin
    
    class MyModelAdmin(admin.ModelAdmin):
        pass
    
    register(MyNeomodel, MyModelAdmin)
  9. classproperty decorator

    master

    The classproperty decorator allows you to define a property that is accessed at the class level, similar to how @property works for instances. In django-neomodel, this is used to implement the _meta attribute on DjangoNode classes.

    from django_neomodel import classproperty
    
    class MyModel:
        @classproperty
        def my_class_attr(self):
            return "value"
    
    # Accessed via the class, not an instance
    print(MyModel.my_class_attr)