0

I would like to create a pipeline instance and create the corresponding input file together. My models I have a structure like this.

class Pipeline(models.Model):
    input_file = models.OneToOneField(
                   'InputFile', 
                   on_delete=models.CASCADE, 
                   null=False, 
                   parent_link=True
                 )


class InputFile(models.Model):
   pipeline = models.OneToOneField(
                  'Pipeline', 
                  on_delete=models.CASCADE, 
                  null=False,  
                  parent_link=False
              )

I tried different combinations of parent_link=True/False, but nothing worked. Only if I set parent_link=True everywhere both instances are created, however, then it is impossible to delete them again.

My admin.py looks like:

class InputFileAdmin(admin.StackedInline):
    model = InputFile

class PipelineAdmin(admin.ModelAdmin):
    inlines = [Inputfile]

admin.site.register(Pipeline, PipelineAdmin)

Whatever combination I always get errors either during creation or deletion.

Soerendip
  • 7,684
  • 15
  • 61
  • 128
  • Pro tip: you only need to declare `OneToOneField` in one of the model classes, not both. – Code-Apprentice Apr 16 '21 at 18:12
  • That depends on the usecase. I actually have more complex models than these here. And I need a reference to the parent to define a target path etc. – Soerendip Apr 16 '21 at 18:14
  • The single declaration will automatically create a field for the parent in the related model. See the examples [here](https://docs.djangoproject.com/en/3.1/topics/db/examples/one_to_one/). Notice how `place` is only declared in `Restaurant` and `p2.restaurant` is automatically created for the reverse relationship. – Code-Apprentice Apr 16 '21 at 18:15
  • Yes, but how would I reference that directly in the model? There are model properties that depend on pipeline. The field would be there but there would be no option to reference it.https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.OneToOneField.parent_link that is when the `parent_link` should be used. Or do I misunderstand something? – Soerendip Apr 16 '21 at 19:24

1 Answers1

0

I the problem was the on_delete argument. On delete the framework didn't now what to delete first.

This now works:

class Pipeline(models.Model):
    input_file = models.OneToOneField(
                   'InputFile', 
                   on_delete=models.SET_DEFAULT, 
                   null=True,
                   default='', 
                   parent_link=True
                 )


class InputFile(models.Model):
   pipeline = models.OneToOneField(
                  'Pipeline', 
                  on_delete=models.CASCADE, 
                  null=True,  
                  parent_link=False
              )
Soerendip
  • 7,684
  • 15
  • 61
  • 128