[Answered ]-Deleting SQL data in associated OneToOneField model from admin

1๐Ÿ‘

โœ…

Got it cleaned up and working!

My model:

class Party(models.Model):
    name = models.CharField(max_length=100)
    ...

class Person(models.Model):
    party = models.OneToOneField(Party, editable=False)
    firstName=models.CharField(max_length=60)
    lastName=models.CharField(max_length=60)

    def delete(self):
        d = self.party.id
        Party.objects.get(id__exact=d).delete()

My admin:

class PersonAdmin(admin.ModelAdmin):
    actions=['really_delete_selected']

    def get_actions(self, request):
        actions = super(PersonAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

    def really_delete_selected(self, request, queryset):
        for obj in queryset:
            obj.delete()

        if queryset.count() == 1:
            message_bit = "1 person was"
        else:
            message_bit = "%s people were" % queryset.count()

        self.message_user(request, "%s successfully deleted." % message_bit)
        really_delete_selected.short_description = "Delete selected entries"
        ...
๐Ÿ‘คreK1NDLE

1๐Ÿ‘

I am getting a feeling that it should be as simple as switching the sequence of deleting the two (unless you have tried this already). Since the person is associated with party, once you delete person, you cannot access party. Hence you should do

person.party.delete()
person.delete()
๐Ÿ‘คPriyeshj

Leave a comment