[Answered ]-Making a smart class factory in Django

2👍

Django Tagging has a great example in the models.py as to how it figures out the content type of specific classes. I’m currently using the pattern in another module I developed with permissions.

0👍

You could just subclass your Product, as documented here: http://docs.djangoproject.com/en/1.2/topics/db/models/#model-inheritance

class OtherProduct(Product):
    battery_life = …

Maybe also make Product an abstract base class if you don’t need to use it directly.

0👍

You could use entity framework with generic relations. For example, in models.py:

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

# Product
class Product(models.Model):
    name = models.CharField(max_length=128)
    pub_date = models.DateTimeField('date published', null=True)
    productDescription = models.CharField(max_length=400)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')


#Shirt Product type
class ShirtProduct(models.Model):
    product  = generic.GenericRelation(Product)



#Book Product type
class BookProduct(models.Model):
    product  = generic.GenericRelation(Product)

….

For search one product id, you can use this method in your ProductManager:
product = generic.GenericRelation(Product,
content_type_field=’content_type_fk’,
object_id_field=’object_primary_key’)

(reverse generic relations in the same section of djangoproject page)

👤rcc-e

Leave a comment