In my app, I have a model called Supplier and multiple models like Part, Fuel, Ink, etc., which are all a some form of resource that a supplier might supply.
I want to be able to fetch all resources for a given supplier, and figured I would implement this efficiently by making a SupplierResource model with two fields: supplier and resource (resource be a foreign key to an object in either one of the "resource" tables).
But this, does not seem to work, because I can't create a foreign key that maps to different models.
Here are example models:
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)
I could iterate through all child models of Resource to collect resources for a given supplier but that would be very slow.
I would prefer not using polymorphism to avoid unnecessary complexity (unless it turns out this is strictly necessary).