我一直在努力了解如何让多对多关系正常运作。这是实体和事件的简化模型。我试图建模的关系是:
从查找角度来看,到目前为止这是有效的:
但我无法弄明白:
查找与此事件有关系的实体(反向/向后关系)
class Entity2EntityRel(Model):
from_entity = ForeignKey('Entity', to_field='uuid',
related_name="from_entity")
to_entity = ForeignKey('Entity', to_field='uuid',
related_name="to_entity")
relation = CharField(max_length=64)
def __unicode__(self):
return json.dumps({
"from_entity": str(self.from_entity),
"relation": str(self.relation),
"to_entity": str(self.to_event)
})
class Entity2EventRel(Model):
from_entity = ForeignKey('Entity', to_field='uuid',
related_name="from_entity_ev")
to_event = ForeignKey('Event', to_field='uuid',
related_name="to_event_en")
relation = CharField(max_length=64)
def __unicode__(self):
return json.dumps({
"from_entity": str(self.from_entity),
"relation": str(self.relation),
"to_event": str(self.to_event)
})
class Entity(PolymorphicModel):
uuid = UUIDField(unique=True)
name = CharField(max_length=255, unique=True)
entity_rels = ManyToManyField(
'Entity',
through='Entity2EntityRel',
related_name="related_entity_set",
symmetrical=False)
event_rels = ManyToManyField(
'Event',
through='Entity2EventRel',
related_name="related_event_set",
symmetrical=False)
def add_entity_rel(self, entity, relation_name):
relationship, created = Entity2EntityRel.objects.get_or_create(
from_entity=self,
to_entity=entity,
relation=relation_name)
return relationship
# return entities related to me
def get_entity_rels(self, relation_name):
return self.entity_rels.filter(
to_entity__relation=relation_name,
to_entity__from_entity=self)
# return items that have a relation to me
def get_related_entities(self, relation_name):
return self.related_entity_set.filter(
from_entity__relation=relation_name,
from_entity__to_entity=self)
def add_event_rel(self, event, relation_name):
relationship, created = Entity2EventRel.objects.get_or_create(
from_entity=self,
to_event=event,
relation=relation_name)
return relationship
# return events related to me
def get_event_rels(self, relation_name):
return self.event_rels.filter(
to_event_en__relation=relation_name,
to_event_en__from_entity=self)