Django:无法使用映射到不同模型的字段创建模型

标签 django django-models database-design

在我的应用程序中,我有一个名为 Supplier 的模型和多个模型,例如 PartFuelInk等,它们都是供应商可能提供的某种形式的资源

我希望能够获取给定供应商的所有资源,并认为我可以通过制作一个包含两个字段的 SupplierResource 模型来有效地实现这一点:supplierresource(resource 是任一“资源”表中对象的外键)。

但这似乎不起作用,因为我无法创建映射到不同模型的外键。

以下是示例模型:

class Supplier(models.Model):
    delivery_time = models.CharField(max_length=255, blank=True, null=True)
    minimum_order_quantity = models.FloatField(blank=True, null=True)
    billing_address = models.ForeignKey(...)
    shipping_address = models.ForeignKey(...)
    # ...


class Resource(models.Model):
    code = models.CharField(max_length=255, unique=True, blank=True, null=True)
    supplier = models.ForeignKey(
        Company,
        related_name="supplier_part",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    country = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        abstract = True

class Part(Resource):
    some_attr = models.CharField(max_length=255, blank=True, null=True)


class Fuel(Resource):
    some_other_attr = models.CharField(max_length=255, blank=True, null=True)

我可以遍历 Resource 的所有子模型来收集给定供应商的资源,但这会非常慢。

我宁愿不使用多态性以避免不必要的复杂性(除非事实证明这是绝对必要的)。

最佳答案

你可以考虑使用django-polymorphic .

如果这样做,只需让 Resource 像这样从 PolymorphicModel 继承:

from polymorphic.models import PolymorphicModel

class Supplier(models.Model):
    delivery_time = models.CharField(max_length=255, blank=True, null=True)
    minimum_order_quantity = models.FloatField(blank=True, null=True)


class Resource(PolymorphicModel):
    code = models.CharField(max_length=255, unique=True, blank=True, null=True)
    country = models.CharField(max_length=255, blank=True, null=True)


class Part(Resource):
    some_attr = models.CharField(max_length=255, blank=True, null=True)


class Fuel(Resource):
    some_other_attr = models.CharField(max_length=255, blank=True, null=True)

然后您可以像下面这样创建 SupplierResource 模型:

class SupplierResource(models.Model):
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE)

或者,Supplier 和 Resource 之间的多对多关系:

class Supplier(models.Model):
    delivery_time = models.CharField(max_length=255, blank=True, null=True)
    minimum_order_quantity = models.FloatField(blank=True, null=True)
    resources = models.ManyToManyField(Resource, related_name="suppliers")

关于Django:无法使用映射到不同模型的字段创建模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70851367/

相关文章:

python - 用于计算列计数的不同组合的 Django 对象查询

python - Django 管理错误

python - 为创建 Django 模型实例添加日志记录的最佳方法是什么?

django - 如何在 django-admin 中添加自定义按钮

mysql - 使用mysql在django模型charfield中获取空白语句

database - 识别一对多关系

django - Heroku:未找到 PIL==1.1.7 的匹配分布

angularjs - jwt token 刷新如何在 django REST Angular 中工作

database - "A parent object will have up to 2 children"之类的规则是否应该在数据库中重复

mysql - 具有相似列/属性的设计表