Package: django-relativity
django-relativitydjango-relativity provides aRelationshipfield that lets you declare the non-foreign-key relationships between your models and use them throughout the ORM.Non-foreign-key relationships?Like the relationship between a node and its descendants in a tree, or between two tagged items that share a tag. Almost anything you can express with Django's filter syntax, you can use to define a relationship.Use them throughout the ORM?Yes, across joins, infilter(), in methods likeprefetch_related()orvalues()- anywhere Django expects to see a field.What problem does this solve?Sometimes the relationships between our models are more complex than equality between a primary key field on one model and a foreign key on another.For example: when working with trees, we very often need to find a given node's descendants - its children, their children, and so on. The exact query we have to run depends on how we've chosen to implement our tree structure at the database level, and fortunately there are mature libraries available to take care of that for us.django-mpttanddjango-treebeardboth provide methods calledget_descendants()for exactly this purpose. These return a queryset selecting the node's descendants, which we can then filter further, or use as an argument to another filter, and so on. So what's the problem?The problem is that the node-descendants relationship is invisible to the Django ORM. We can't filter against it, likeNode.objects.filter(descendants__in=objs). We can't traverse it, likeNode.objects.filter(descendants__name__startswith="A"). We can't prefetch it. None of the niceties that Django provides for working with relationships are available for us to use with this relationship, because it can't be declared as aManyToManyFieldorForeignKey.django-relativity lets all those ORM features work with almost any kind of relationship you can dream up.MPTT and treebeard helpersIf you use django-mptt or django-treebeard and you want to jump right in, relativity comes with fields to select a node's descendants and its subtree (which respectively exclude and include the current node). The default reverse relation names for these fields areascendantsandrootpath.# For django-mpttfromrelativity.mpttimportMPTTDescendants,MPTTSubtree# for treebeard with materialised pathfromrelativity.treebeardimportMP_Descendants,MP_Subtree# for treebeard with nested setsfromrelativity.treebeardimportNS_Descendants,NS_SubtreeclassTreeNode(MPTTModel):...# after defining all your other fields, including TreeForeignKey...descendants=MPTTDescendants()subtree=MPTTSubtree()What does the code look like?Here are some models for an imaginary website about chemistry, where users can filter compounds by regular expression and save their searches:fromrelativity.fieldsimportL,RelationshipclassChemical(Model):common_name=TextField()chemical_name=TextField()formula=TextField()classSavedFilter(Model):user=ForeignKey(User)search_regex=TextField()chemicals=Relationship(to=Chemical,predicate=Q(formula__regex=L('search_regex')),)Now I can use that field like this:my_filter.chemicals.all()# all the chemicals whose formulae match this filtermy_chemical.saved_filters.all()# all the filters whose regexps match this chemicalmy_user.filter(saved_filters__chemicals=my_chemical)# users with filters matching this chemicalmy_chemical.filter(saved_filters__user=my_user)# chemicals in any of this user's filtersIn short, I can use it just like a normal Django relation. It provides forward and reverse properties that return Managers, and I can use it in filters spanning multiple models.How does thatRelationshipfield work?ARelationshipbehaves like aForeignKeyorManyToManyFieldand defines a relationship with another model. Unlike the built-in Django relations,Relationshipdoesn't use its own database column or table to determine which instances are related. Instead, you give it an arbitrarypredicate, expressed as a normal DjangoQ, which determines which instances of thetomodel are in the relationship.What's thatLdoing there?In Django ORM expressions,Fis a reference to a field on the model being queried.Lis similar, but refers to a field on the model on which theRelationshipis defined. Think of it as L for theleft-handside of a join, or L for thelocalmodel.Going back to our example - thechemicalsfield provides the set ofChemicals whose formulae match theSavedFilter's regular expression.Let's make some chemicals:>>>Chemical.objects.create(name="baking soda",formula="NaHCO3")...Chemical.objects.create(common_name="freon",formula="CF2Cl2")...Chemical.objects.create(common_name="grain alcohol",formula="C2H5OH")...Chemical.objects.create(common_name="quartz",formula="SiO2")...Chemical.objects.create(common_name="salt",formula="NaCl")Now, say I'm a user who's interested in chemicals containing chlorine. Simple enough:>>>chloriney=SavedFilter.objects.create(user=alex,search_regex=r'Cl')>>>chloriney.compounds.all()<QuerySet[<Chemical:CF2Cl2>,<Chemical:NaCl>]>Anne is interested in oxides, so her regex is a bit more complicated:>>>oxides=SavedFilter.objects.create(user=anne,search_regex=r'([A-Z][a-z]?\d*)O(\d+|(?!H))')>>>oxides.compounds.all()<QuerySet[<Chemical:NaHCO3>,<Chemical:SiO2>]>Now, this is nothing you couldn't do with a helper method onSavedFilterwhich returns the appropriate QuerySet. But now we add a new chemical to our database, and we want to identify users who are interested in that chemical so we can notify them:>>>added_chemical=Chemical.objects.create(common_name="chlorine dioxide",chemical_name="chlorine dioxide",formula="ClO2")<Chemical:ClO2>>>>User.objects.filter(saved_filters__chemicals=added_chemical)<QuerySet[<User:alex>,<User:anne>]>This is why I call django-relativity aforce-multiplierfor the ORM.Relationships work with the ORM just likeForeignKeys orManyToManyFields. You can traverse them and filter on them just like you can with the built-in relationship fields. The goal of django-relativity is forRelationships to be able to do anything a normal Django relationship field can do.Reverse relationsRelationships work in the reverse direction as well, with the same naming behaviour as Django's fields: the default related name is<model_name>_setor<model_name>depending on arity, overridable with therelated_nameargument.related_query_nameworks as well.In the example above,my_chemical.saved_filter_set.all()will return all of theSavedFilters matchingmy_chemical.Chemical.objects.filter(saved_filters__user=alex)will select all of the chemicals in all of my saved filters.ArityRelationships between models can be one-to-one, one-to-many, many-to-one, or many-to-many.Relationshipcan express all of those, using themultipleandreverse_multiplearguments. Both default toTrue.Here's a many-to-one example - many cart items can be associated with each product, but only one product is associated with each cart item.classCartItem(models.Model):product_code=models.TextField()product=Relationship(to=Product,predicate=Q(sku=L('product_code')),multiple=False,)What state is this project in?This project is used in production and in active development. Things not covered by the tests have every chance of not working.Migrating from relativity < 0.2.0Before 0.2.0, it was necessary to import a backported version ofdjango.db.models.Qfromrelativity.compatin order to make migrations work in Django 1.11. From 0.2.0 onwards, that's no longer necessary. The backportedQstill exists as an alias to django.db.models, but a DeprecationWarning will be issued on import. You should replace all uses with Django's standardQ.From 0.2.0 onwards, relativity's fields do not generate migrations. When migrating from older versions, I recommend simply removing all references to relativity's fields from the original migrations that created them, rather than generating new migrations removing the virtual fields.