在我的应用程序中,我有一个名为 Supplier
的模型和多个模型,例如 Part
、Fuel
、Ink
等,它们都是供应商可能提供的某种形式的资源。
我希望能够获取给定供应商的所有资源,并认为我可以通过制作一个包含两个字段的 SupplierResource
模型来有效地实现这一点:supplier
和 resource
(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/