def __init__(self, instance=None, bind=False, *args, **kwargs):
self._instance = instance
self.__recursion_depth__ = 0
defaults = {key: getattr(self._instance, key, kwargs.get(key, None))
for key, _ in self.__all_properties__}
kwargs.update(defaults)
super(ModelNodeMixinBase, self).__init__(self, *args, **kwargs)
# Never try to bind ignore nodes
if bind and self._is_ignored:
bind = False
# Query the database for an existing node and set the id if found.
# This will make this a "bound" node.
if bind and not hasattr(self, 'id'):
required = {key: prop for key, prop in self.defined_properties(aliases=False, rels=False).items()
if prop.required or prop.unique_index}
if all(getattr(self, attr) for attr in required.keys()):
node_id = self._get_id_from_database(self.deflate(self.__properties__))
if node_id:
self.id = node_id
if not self._instance and self.pk:
self._instance = self.get_object(self.pk)
if self._instance:
# For GenericForeignKey fields, we have no way of knowing what kind of
# object it is related to during class creation, thus the relationship
# definition is set to refer itself.
# When initializing we have access to the underlying django object instance and
# can inspect it, so we need to switch out the relationship definition
# node class in order to connect to the correct node.
from chemtrails.neoutils import get_node_class_for_model
generic_fks = filter(lambda f: isinstance(f, GenericForeignKey),
self.get_forward_relation_fields())
for field in generic_fks:
relationship = self.defined_properties(aliases=False, properties=False).get(field.name, None)
if isinstance(getattr(self._instance, field.name, None), models.Model) and relationship:
node_class = get_node_class_for_model(getattr(self._instance, field.name))
model = relationship.definition['model']
model.target_field.default = str(node_class._pk_field).lower()
# defensively set the definition dictionary to a dict like class
# which will protect the safeguarded keys against being copied over
# by neomodel
relationship.definition = DefinitionDict(relationship.definition)
relationship.definition._safeguard('node_class', node_class)
relationship.definition._safeguard('model', model)
评论列表
文章目录