【问题标题】:How can I create a ForeignKey leaving chances for different models for the TO field?如何为 TO 字段的不同模型创建 ForeignKey 留下机会?
【发布时间】:2020-12-31 02:21:33
【问题描述】:

我有多种产品型号,如下所示

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 类中的产品字段根据需要指向上面定义的任何产品。

【问题讨论】:

    标签: python django django-models database-relations


    【解决方案1】:

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

    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 模型即可。我相信这是一种更简洁的实现方式,因为在这种情况下实际上不需要多个模型。

    【讨论】:

      【解决方案2】:
      class Image(models.Model):
          product = models.ForeignKey(ProductOne, on_delete=models.CASCADE)
          image = models.ImageField(upload_to='upload-path')
      

      没有“to”属性,您只需将其引用到您想要的模型

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-15
        • 2020-06-06
        • 2015-11-30
        • 2021-12-23
        • 2020-06-08
        • 2017-03-05
        • 2018-01-10
        相关资源
        最近更新 更多