2011-03-08 18 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相同的部分通用關係)