我已经尝试解决这个问题有一段时间了,但收效甚微。我正在尝试编写一个与Django的ORM配合得很好的类工厂,这样我就可以采用如下的模型模式:
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...but我不知道怎么做才是“正确的”。有没有人能在这里说点什么?
发布于 2011-03-08 19:16:15
关于如何确定特定类的内容类型,Django Tagging在models.py中有一个很好的例子。我目前正在使用我开发的另一个有权限的模块中的模式。
发布于 2011-03-08 23:53:10
您只需将Product子类化即可,如下所示:http://docs.djangoproject.com/en/1.2/topics/db/models/#model-inheritance
class OtherProduct(Product):
battery_life = …如果你不需要直接使用Product,也可以让它成为一个抽象基类。
发布于 2014-01-04 01:03:02
您可以使用具有泛型关系的实体框架。例如,在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中使用此方法: product = generic.GenericRelation( product,content_type_field='content_type_fk',object_id_field='object_primary_key')
(在djangoproject page的同一节中颠倒泛型关系)
https://stackoverflow.com/questions/5231556
复制相似问题