Login

Generic Model

Author:
hakejam
Posted:
March 1, 2007
Language:
Python
Version:
Pre .96
Score:
0 (after 0 ratings)

In this type of model you are allowed to define a model with a generic type.

For instance, a location can be an address, GPS coordinates, an intersection and many others types. Using a many to many field, models can have multiple locations without worrying about the type of location referencing. New locations types can be added without changing the references in other models.

This code is also used in Django's built in ContentTypes app.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.db import models

class GenericModel(models.Model):
	app_name = models.CharField(maxlength=64)
	model_name = models.CharField(maxlength=64)
	object_id = models.IntegerField()
	
	def get_model_class(self):
		return models.get_model(self.app_name, self.model_name)
	
	def get_this_object(self):
		return self.get_model_class()._default_manager.get(**kwargs)
	
	def __str__(self):
		return self.get_this_object().__str__()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

ubernostrum (on March 1, 2007):

Also, note that the GenericForeignKey field included in Django allows a fairly clean implementation of this.

#

Please login first before commenting.