How to estabilish ContentType relation in Django for Laravel Polymorphic related data?

160 views Asked by At

I have a database that was created and working for the Laravel application, it contains a table with shared data for multiple models using "Laravel Polymorphic Relationships"

For example, this is Comment model that contains comments for the Product, Post, Seller.

id commentable_type commentable_id Comment
1 App\Product 1 Comment text
2 App\Product 2 Comment text
3 App\Seller 1 Comment text

I need to use this table in the Django application, I tried to create relation using ContentType Framework but no success because it's requires ContentType (int) relation to determine the model, but in the database, I have string values for _type. Any suggestions on how to deal with it?

1

There are 1 answers

0
TruthTeller On

After following the official documentation, you will see content_type_id in your polymorphic model's db table. This field references to the table django_content_type.id which is a list of models for each app in your project:

id app_label model
1 auth user
2 app product
3 app seller

Django uses an id (int) reference to the parent model whereas Laravel saves the parent's model class name as a string field. This is why you will find content_type_id and not content_type once you migrate your migrations.

This answer might also help you understand Generic relation better.