一对一的关系,但Django中有多种类型



我正在用Django创建一个在线商店。我想,由于可能有不同类型的待售物品共享一些属性和字段,我最好制作一个物品模型和其他模型的子类。所以我现在有一个抽象的项目模型和其他一些模型,如连衣裙,裤子和鞋子。现在我想要一个新的模型(例如Comment(,它应该与Item模型有关系。但由于Item模型是抽象的,所以我做不到。有没有办法让我有一种一对一的关系,一方可以接受不同的类型?类似这样的东西:

class Comment(models.Model):
item = models.ForeignKey(to=[Dress, Pants, Shoes])

一个Foreing key字段只能导致一个instance,在数据库中它看起来是这样的:

|id|  item |
|13|t-shirt|    

解决问题的最佳方法是使用以下三种模型:

class Item_type(models.Model):
#here you should create as many instances as you have types of your items
# one item_type = Dress, second = Pants, third = Shoes
title = models.CharField(max_length=50)
class Item(models.Model):
#here you create your item, with title for example Nike Brand new shooes
title = models.CharField(max_length=150)
#and choosing type in oneToOneField = shooes
item_type = models.OneToOneField(Item_type, on_delete=models.CASCADE)

class Comment(models.Model):
#here you have your comments for your Item
item = models.ForeignKey(Item, on_delete=models.CASCADE)

Generic Relations听起来像是解决方案,在Comment模型中添加以下字段:

class Comment(models.Model):
[Other fields]
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()

在抽象的Item模型中添加GenericRelation字段

class Item(models.Model):
[Other fields]
comments = GenericRelation(Comment)

class Meta:
abstract=True

最新更新