2011-03-08 38 views
1

我一直试图找出一段时间,现在取得一点成功。我试图写一个类工厂,起着很好的Django的ORM,这样我就可以采取这样的模型模式:在Django创建一个智能类工厂

Product 
    SubclassOfProduct0 
    SubclassOfProduct1 
    .... 

要像这样工作:

Product.objects.get(pk=7) // returns the result of SubclassOfProduct0(pk=7) 
Product.objects.filter(propname="w00t") // returns a QuerySet of Product objects 

所以我就在想这样的事情:

class ProductManager(models.Manager): 
    def get(self, *a, **kwa): 
     # Get the id from Products (somehow) 
     if product.type == Product.TYPE_SUBCLASS0: 
      return ProductSubClass0.objects.get(pk=kwa["pk"]) 


class Product(models.Model): 

    TYPE_SUBCLASS0 = 0 
    TYPE_SUBCLASS1 = 1 

    objects = ProductManager() 

    def __init__(self, *a, **kwa): 
     self.set_defaults() 

    def set_defaults(self): 
     pass 


class ProductSubClass0(models.Model): 
    def set_defaults(self): 
     self.type == self.TYPE_SUBCLASS0 

...但我不知道如何做到“正确”。有人可以在这里发光吗?

+0

不要这样做。你不需要写一个工厂。只需创建层次结构并通过ORM创建对象。 – 2011-03-08 11:19:17

+0

通常情况下,我会同意,但如果我不这样做,它会迫使我在我需要有关对象的其他信息并且只有该ID时将这种逻辑放在我的视图中。例如,在REST调用中,用户提供pk = 7,我必须返回ProductSubClass的一个实例。 – 2011-03-08 11:42:54

+0

ProductSubClass与Product类具有相同的字段吗? – 2011-03-08 13:14:10

回答

2

Django Tagging在models.py中有一个很好的例子,它是如何计算出特定类的内容类型的。我目前正在使用我开发的另一个模块中的模式使用权限。

+0

这实际上比我想象的要多得多。我最终写了一个名为acquire()的方法到一个新的ProductManager()中,该方法从db中选择'type',其中pk = 。然后,通过这个,我导入了相应的类并返回了ProductSubClass0.objects.get(pk = n)的输出。 – 2011-03-08 15:42:16

0

您可以使用具有一般关系的实体框架。例如,在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) 

....

对于搜索一个产品ID,您可以在ProductManager使用此方法: 产品= generic.GenericRelation(产品, content_type_field = 'content_type_fk', object_id_field = 'object_primary_key')

(逆转的djangoproject page相同的部分通用关系)