Login

Tag "inheritance"

Snippet List

Inherit the standard url tag to include domain name

This module extends the standard `url' template tag in Django and adds support for fully qualified domain name URLs. It also can be extended with simple URL load balancing techniques if desired. See my blog for the background story: <http://atodorov.org/blog/2013/12/22/django-template-tag-inheritance-howto/>

  • template
  • tag
  • templatetag
  • url
  • inheritance
Read More

Get derived model instance

Get derived model without storing their names or content types in databases. You write only one line, it expands into only one SQL-query (with many LEFT OUTER JOIN's). Model definition example: class BaseModel(models.Model): foo = models.IntegerField(null=True) derived = DerivedManager() class FirstChild(BaseModel): bar = models.IntegerField(null=True) class SecondChild(BaseModel): baz = models.IntegerField(null=True) How to use: >>> f = FirstChild.objects.create() >>> s = SecondChild.objects.create() >>> print list(BaseModel.objects.all() [<BaseModel object 1>, <BaseModel object 2>] >>> print list(BaseModel.derived.all() [<FirstChild object 1>, <SecondChild object 2>] >>> print BaseModel.derived.get(pk=s.pk) <SecondChild object 2>

  • models
  • orm
  • inheritance
Read More

Form and ModelForm inheritance DRY

Modelform cant inhertit from forms. To solve this issue, split thing you wanto to inherit into filed definition and functionality definition. For modelform use the base_fields.update method as mentioned in the code.

  • form
  • inheritance
Read More

Polymorphic inheritance ala SQLAlchemy

This is a different take on polymorphic inheritance, inspired by SQLAlchemy's approach to the problem. The common Django approach (e.g. snippets 1031 & 1034, [django_polymorphic](http://github.com/bconstantin/django_polymorphic)) is to use a foreign key to `ContentType` on the parent model and override `save()` to set the right content type automatically. That works fine but it might not always be possible or desirable, for example if there is another field that determines the "real type" of an instance. In contrast this snippet (which is actually posted and maintained at [gist.github](http://gist.github.com/608595)) allows the user to explicitly specify the field that determines the real type of an instance. The basic idea and the terminology (`polymorphic_on` field, `polymorphic_identity` value) are taken from [SQLAlchemy](http://www.sqlalchemy.org/docs/orm/inheritance.html). Some other features: * It works for proxy child models too, with almost no overhead compared to non-polymorphic managers (since there's no need to hit another DB table as for multi-table inheritance). * It does not override the default (or any other) model Manager. Regular (non-polymorphic) managers and querysets are still available if desired. * It does not require extending a custom Model base class, using a custom metaclass, monkeypatching the models or any kind of magic.

  • inheritance
  • polymorphic
Read More

Child aware model inheritance

Base models aren't aware of its inherited models, here is a quick solution to access child models from the base model.

  • model
  • inheritance
  • child
  • content-type
Read More
Author: rix
  • 2
  • 4

extends_default

Works exactly like the standard "extends" tag but enables one to fallback on a default template. This tag is LIMITED, as it falls back to the next template with the same name that DOES NOT contain "extends_default" (does NOT simulate full inheritance, just a single level). A partial solution to problems like http://jeffcroft.com/blog/2008/aug/05/default-templates-django/. MIT licensed.

  • template
  • templatetag
  • inheritance
  • default
Read More

ParentModel and ChildManager for Model Inheritance

This is the approach I've taken to access instances of child models from their parent. Functionally it's very similar to snippets [1031](http://www.djangosnippets.org/snippets/1031/) and [1034](http://www.djangosnippets.org/snippets/1034/), but without the use of `django.contrib.contenttypes`. Usage: class Post(ParentModel): title = models.CharField(max_length=50) objects = models.Manager() children = ChildManager() def __unicode__(self): return self.title def get_parent_model(self): return Post class Article(Post): text = models.TextField() class Photo(Post): image = models.ImageField(upload_to='photos/') class Link(Post): url = models.URLField() In this case, the `Post.children` manager will return a queryset containing instances of the appropriate child model, rather than instances of `Post`. >>> Post.objects.all() [<Post: Django>, <Post: Make a Tumblelog>, <Post: Self Portrait>] >>> Post.children.all() [<Link: Django>, <Article: Make a Tumblelog>, <Photo: Self Portrait>]

  • model
  • manager
  • queryset
  • inheritance
Read More

Model inheritance with content type and inheritance-aware manager

inspired by crucialfelix's [inheritance hack](http://www.djangosnippets.org/snippets/1031/), which was a far better method of fetching a model's subclassed version from an instance than my own, i decided to bake his snippet in to my own inheritance hack, which i think benefits both. the result is a query set that returns subclassed instances per default. So - in the snippet's example, querying `Meal.objects.all()[0]` will return a salad object, if that instance of Meal happens to be the parent of a Salad instance. To my mind this is closer to the 'intuitive' way for a query set on an inheriting model to behave. **Updated:** added subclassing behaviour for the iterator access as well. **Updated:** incorporated carljm's feedback on inheritance

  • manager
  • inheritance
Read More

Model inheritance with content type

Contact is a parent class. Subclasses might be Company, Person, Artist, Label etc. Basic address, email etc. fields can be added to the parent class and all subclasses will have those. Having searched your database for contacts (undifferentiated by class) you then want to reload the chosen object as the subclass that it really is : ``thing.as_leaf_class``

  • inheritance
Read More

Custom Django manager that excludes subclasses

When you're using Django model inheritance, sometimes you want to be able to get objects of the base class that aren't instances of any of the subclasses. You might expect the obvious way of doing this, `SuperModel.objects.filter(submodel__isnull=True)`, to work, but unfortunately it doesn't. (Neither does `SuperModel.objects.filter(submodel__supermodel_ptr=None)`, or any other convoluted way I could think of doing it.) Here's a nicer approach for doing this. [The blog entry is here.](http://sciyoshi.com/blog/2008/aug/07/custom-django-manager-excludes-subclasses/)

  • managers
  • models
  • model
  • subclass
  • manager
  • inheritance
  • subclasses
Read More

Multiple inheritance of newforms and modelforms

If you try to use multiple inheritance with a modelform (to mix in some fields from an already existing form class for example) you'll get the following rather terrifying error: > "Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases" The solution is to first create the ModelForm, then create a NEW class that inherits from both the ModelForm and the form you want to mixin, then finally apply the recipe from here: [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197](http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197)

  • newforms
  • inheritance
  • modelforms
  • multipleinheritance
  • metaclasses
  • metaclass
Read More

Django Model Inheritance

This snippet shows an alternative and interesting way to do Model Inheritance in Django. For description of the code, follow the inline comments.

  • model
  • inheritance
Read More

DRY with common model fields

If you have many models that all share the same fields, this might be an option. Please note that order matters: Your model need to inherit from TimestampedModelBase first, and models.Model second. The fields are added directly to each model, e.g. while they will be duplicated on the database level, you only have to define them once in your python code. Not sure if there is a way to automate the call to TimestampedModelInit(). Tested with trunk rev. 5699. There is probably a slight chance that future revisions might break this.

  • models
  • model
  • inheritance
Read More

13 snippets posted so far.