Django3: How to setup OneToOneField that works with inline admin correctly?

60 views Asked by At

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.

1

There are 1 answers

0
Soerendip On

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
              )