Login

Snippets by christhekeele

Snippet List

RelatedMixin for Details and Updates with Related Object Lists

Code for a RelatedMixin I whipped up, useful in instances where you wish to expose details of a single object, including a related group of owned objects, in the same view. Works well with Django's generic DetailView and UpdateView, or any subclass of SingleObjectMixin. It's a little cleaner than overriding get_context_data differently for every model you want to expose, uses `only('id')` on querysets it doesn't need anything but relational data from, and makes pulling ownership out of distantly related objects much easier. Supports simple nested hierarchies of models, ie: * View a company and all people belonging to it Detail(Company < People) * Edit a company and all computers belonging to its members Update(Company < People < Computers). Tested with non-generic One-To-Many and reverse object_sets only. Just provide an OrderedDict called `related_chain` in your DetailRelatedView that describes the progression of querysets to follow, in the format: model=Foo, relation_chain=OrderedDict([ ('foreign_key_from_foo_to_bar',Bar.objects.all()), ('foreign_key_from_baz_to_bar',Baz.objects.all()) ]) It also takes two optional attributes: context_list_name="baz_list" which provides an alias for the final related `object_list` (default=`related_list`), and keep_intermediaries=True which, if providing a list deeper than one relation, also passes any intermediary related lists into the context, named after the connecting foreign key, like `bar_list` (default=False).

  • mixin
  • model-filtering
  • class-based-generic-view
Read More

christhekeele has posted 1 snippet.