我有一个简单的产品数据库,如下所示:
class Product(models.Model):
sku = models.CharField(max_length=200)
name = models.CharField(max_length=200)
price = models.CharField(max_length=200)
class meta:
abstract = True
class Shoe(Product): #inherits from product
size = models.CharField(max_length=200)
class Computer(Product): #inherits from product
cpu = models.CharField(max_length=200)这将在DB...Shoe和Computer中留下两个表。现在,如果我想按类别对它们进行组织该怎么办?就像在have a Category model中一样,它有一个好的人类可读的名字,一个显示在产品下拉菜单上的图标,诸如此类。我迷路了!鞋和电脑是不同的models...so一个模型(类别)如何组织它们?
半个人?
发布于 2013-11-17 11:11:10
只需将以下代码放入Product:
category = models.ForeignKey(Category, related_name='%(class)s_set')您可以了解有关外键here的更多信息。
发布于 2013-11-17 12:29:18
也许你可以使用Generic Foreign Keys
class Category(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
name = models.charField(max_length=50)
class Product(models.Model):
categories = generic.GenericRelation(Category)我不太确定你对类别的想法是什么,但你可以创建新的类别,引用任何对象,计算机或鞋子
shoe = Shoe.object.get(pk=1)
category = Category(content_object=shoe, name='tennis')
category.save()
category = Category(content_object=shoe, name='waterproof')
category.save()
shoe.catetories.all()https://stackoverflow.com/questions/20026350
复制相似问题