I would like to create a slightly more complex data model in TortoiseORM which is proving to be quite difficult. The idea of the datamodel is as follows:
Media: Regular table.
class Media(models.Model):
id: str = fields.CharField(max_length=20, pk=True)
type = fields.CharEnumField(MediaType)
url: str = fields.CharField(max_length=512)
thumbnail_url: str = fields.CharField(max_length=512)
medium_thumbnail_url: str = fields.CharField(max_length=512)
order: int = fields.IntField()
product = fields.ForeignKeyField('models.Product', related_name='media', on_delete=fields.CASCADE)
Product: Not a table. Just a mixin.
class Product(models.Model):
id = fields.CharField(max_length=12, pk=True, index=True)
date_created = fields.DatetimeField(auto_now_add=True)
date_last_updated = fields.DatetimeField(auto_now=True)
[...]
description = fields.TextField(null=True)
thumbnail_url = fields.CharField(max_length=512)
medium_thumbnail_url = fields.CharField(max_length=512)
media = fields.ReverseRelation[Media]
class Meta:
abstract = True
Vehicle: Not a table. Just a mixin. Inherits from Product.
class Vehicle(Product):
year = fields.IntField()
make = fields.CharField(max_length=100)
model = fields.CharField(max_length=100)
vin = fields.CharField(max_length=100, null=True)
odometer = fields.IntField()
color = fields.CharField(max_length=100)
class Meta:
abstract = True
Motorcycle: Regular table. Inherits from Vehicle. No new variables.
class Motorcycle(Vehicle):
pass
Parts: Regular table. Inherits from Product. No new variables.
class Parts(Product):
pass
The issue I am running into is the one to many relationship between the different product types and the media objects.
Whenever I try to create the media objects:
if product_create.media:
i, media_objs = 0, []
for media_obj in product_create.media:
media_obj: MediaCreate = media_obj
media_objs.append(Media(product=product,
id=get_random_alphanumeric_string(20),
type=media_obj.type,
url=media_obj.url,
thumbnail_url=media_obj.thumbnail_url,
medium_thumbnail_url=media_obj.medium_thumbnail_url,
order=i))
i += 1
await Media.bulk_create(media_objs)
I run into an error with:
line 119, in get_related_model
return cls.apps[related_app_name][related_model_name]
KeyError: 'Product'
[...]
tortoise.exceptions.ConfigurationError: No model with name 'Product' registered in app 'models'.
It seems that the challenge here is to create a foreign key relationship in Tortoise ORM that can dynamically reference different models in an inheritance hierarchy.
I tried looking through the Tortoise documentation, but I couldn't find anything on this specifically. Any help would be greatly appreciated.