1

I am writing a Django app that provides a very simple model called Submittable, which users of the app are supposed to inherit from when they want to use other functionalities of the app.

# app1
class Submittable(models.Model):
    is_submitted = models.BooleanField(default=False)

    # other methods here

# app2
class Paper(Submittable):
    # some fields

However, when I add this as a parent to an already existing model in another app and run makemigrations, I am asked to provide a default value to the new field submittable_ptr_id. The problem is, that I want this field to simply point to a new instance of Submittable but I don't know how to do that.

I know, that I could simply edit the migration file created like so:

class Migration(migrations.Migration):
    dependencies = [
        # some dependencies
    ]

    operations = [
        migrations.AddField(
             model_name='Paper',
             name='submittable_ptr_id',
             # here I set default to a function from the Submittable app that just creates a new submittable
             field=models.OneToOneField(auto_created=True, default=app1.utils.create_submittable, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key
    =True, serialize=False, to='app1.Submittable'),
             preserve_default=False
        ),
    ]

But I want to know if I can specify anything somewhere in app1 that makes this happen automatically? I don't want users of the app to have to make this change themselves and instead, whenever someone inherits from Submittable and runs makemigrations the default value should just be set to this callable that creates a new Submittable.

andreashhp
  • 485
  • 2
  • 16
  • Do you require multi-table inheritance or could you use an abstract class instead? – Iain Shelvington Nov 22 '21 at 10:27
  • I need multi-table inheritance, since one of the functions of `app1` is to relate other models to `Submittable`. For example, it provides a `DeadlineTask` that has a relation to a `Submittable`. So abstract classes does not work.. – andreashhp Nov 22 '21 at 11:03

1 Answers1

-1
class Submittable(models.Model):
    
    class Meta:
        abstract = True
    
Nguemeta joel
  • 397
  • 4
  • 5
  • This is not working, since I need to be able to add `ForeignKeys` to `Submittables`. – andreashhp Nov 22 '21 at 11:04
  • You can add a primaryKey to Submittable like this. paper = models.ForeignKeys(Paper, on_delete=models.CASSCADE, related_name='papers' – Nguemeta joel Nov 22 '21 at 11:11
  • But that's the wrong way around. For example, I have a class `DeadlineTask` that should have a `ForeignKey` to `Submittable` and not specifically to `Paper`. This allows me to use `Submittable` as a sort-of polymorphic superclass. – andreashhp Nov 22 '21 at 11:30