[Django]-See if node exists before creating in NeoModel

4👍

You might be looking for one of these batch operations:

3👍

You can use first_or_none to check if a node exists.

Example:

person = Person.nodes.first_or_none(name='James')
if person == None:
    personNew = Person(name='James').save()

2👍

I have created my own query to do that. Check if it helps.

def exists(node=None, property=None, value=None):
    filter_node = (":" + node) if node != None else ''
    filter_value = ("{" + property + ": '" + value + "'}") if property != None and value != None else '' 
    return db.cypher_query("MATCH(n" + filter_node + filter_value + ")" + " return count(n) > 0 as exists;"  )[0][0][0]

exists(node='User')

0👍

bit extending on @raman Kishore’s answer, I did this, cause I wanted to check if object’s exists and also, sometimes I would insert an ID for myself because it came from another DB and I wanted to keep compatibility, so did the following:

class DefaultMixin:
    date_added = DateTimeProperty()
    nodes: NodeSet  # makes pycharm smarter

    def exists(self, **filters):
        if not filters:
            if not self.id:
                raise KeyError('no filters or id provided')
            filters['id'] = self.id
        return bool(self.nodes.first_or_none(**filters))

0👍

I created a decorator over each of my StructuredNode classes, which checks for the node upon initialization.

def check_if_node_exists(node):
    def node_checker(**kwargs):
            result = node.nodes.first_or_none(**kwargs)
            if result == None:
                print("Creating New Node")
                return node(**kwargs).save()
            print("Returning Existing Node")
            return result
  
    return node_checker
        

@check_if_node_exists
class Employee(StructuredNode):
    name = StringProperty()

To call it, just create an instance of the class:

employee1 = Employee(
    name = "test_name"
)

Leave a comment