shared models between different apps on the same project

Hello everyone,
First question in here :slight_smile:
does anyone know how to deal efficiently with apps that share the same model.
Does it always go back to handling the migration files manually, just copying the common model class between two models.py files.
It results either in data loss on database level or one of the table is not even created :

app1_modelnameX , app2_modelnameX :confused:
Django creates the migrations but does not apply it.
an example of the initial migrations in the new app that django ignored or considered it done.

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Species',
            fields=[
                ('species_id', models.SmallIntegerField(primary_key=True, serialize=False)),
                ('scientific_name', models.CharField(blank=True, max_length=50, null=True)),
                ('species_date', models.SmallIntegerField(blank=True, null=True)),
                ('version', models.CharField(blank=True, max_length=50, null=True)),
                ('species_name', models.CharField(max_length=50)),
                ('link_ucsc', models.CharField(blank=True, max_length=10, null=True)),
                ('link_ncbi', models.IntegerField(blank=True, null=True)),
                ('link_ensembl', models.CharField(blank=True, max_length=50, null=True)),
                ('order_id', models.SmallIntegerField(unique=True)),
                ('islowcov', models.SmallIntegerField(default=0)),
            ],
        ),
    ]

Welcome @waelb1000 !

Side Note: When posting code here, enclose the code between lines of three
backtick - ` characters. This means you’ll have a line of ```, then your code,
then another line of ```. This forces the forum software to keep your code
properly formatted. (I have taken the liberty of correcting your original posts.
Please remember to do this in the future.)

No!

Apps can use models from other apps, they just need to be imported where needed.

If this creates an issue, then odds are that these two apps shouldn’t be separate apps to begin with.

1 Like

thanks for the reply,
in fact, I have common models that should be shared between 3 apps that each have their specific models in addition to the common ones.
I know that django ads a prefix appname_model on the database level but that hasn’t happened in my case.
is it better to rename common table ( risk getting redundant data in db ) or is there a guide on how to deal with this kind of issue :confused:

That’s fine.

One app defines the models, the other apps use them by reference.

Again, it’s more likely that you are creating multiple apps unnecessarily.

1 Like