如何为TO字段创建不同模型的ForeignKey剩余机会?

问题描述

我有以下多个产品型号

class ProductBase(models.Model):
    name = models.CharField(max_length=50)
    
    class Meta:
        abstract = True

    def __str__(self):
        return self.name


class ProductOne(ProductBase):
    color = models.CharField(max_length=50)
 

class ProductTwo(ProductBase):
    type = models.CharField(max_length=50)


class ProductThree(ProductBase):
    breed = models.CharField(max_length=50)

预计这些产品中的每一个都有一个image_set,因此我在下面为产品的图像创建了模型

class Image(models.Model):
    product = models.ForeignKey(to=[HERE IS THE PROBLEM],on_delete=models.CASCADE)
    image = models.ImageField(upload_to='upload-path')

如何根据需要使Image类中的product字段指向上面定义的任何产品。

解决方法

class Image(models.Model):
    product = models.ForeignKey(ProductOne,on_delete=models.CASCADE)
    image = models.ImageField(upload_to='upload-path')

没有'to'属性,您只需将其引用到所需的模型即可

,

最好所有产品都只有一个模型,例如:

class Product(ProductBase):
    model = models.CharField(max_length=50)   #here for example you put the individual info from the different types of products
    color = models.CharField(max_length=50,null=True) #add null=True so you don't have to add it for all the products
    etc...

然后,您不需要单独的Image模型,只需将其作为字段添加到Product模型中即可。我相信这是一种更清洁的实现方式,因为在这种情况下并不需要多个模型。