Skip to content
Advertisement

What to use instead of DO_NOTHING to only delete one field?

I want to link two models like this

class t_data(models.Model):
    receiver = models.TextField()
    file_desc = models.TextField()
    file = models.FileField(upload_to='files')

another model :

class transaction_detail(models.Model):
    transaction_id = models.ForeignKey(
        t_data,
        on_delete=models.DO_NOTHING,
        )
    sender=models.TextField()
    receiver = models.TextField()

*yes i am using DO_NOTHING and i have read that it is wrong to use it. But it is not working.

now when a user tries to delete his file, The t_data object should be deleted but the transaction_details should not change.There is nothing specific on my view for deleting objects. Yet, simple example would be

def delete_request(request,id):
    requested = t_data.objects.get(id=id)
    requested.delete()
return HttpResponseRedirect('/requests')

When I try to delete the t_data object it throws an Integrity Error.

Error:

IntegrityError at /accepted/1 FOREIGN KEY constraint failed Request Method: GET Request URL: http://127.0.0.1:8000/accepted/1 Django Version: 3.1.7 Exception Type: IntegrityError Exception Value:
FOREIGN KEY constraint failed Exception Location: C:UsersukfleAppDataLocalProgramsPythonPython39libsite-packagesdjangodbbackendssqlite3base.py, line 413, in execute Python Executable: C:UsersukfleAppDataLocalProgramsPythonPython39python.exe Python Version: 3.9.1 Python Path:
[‘C:UsersukfleDocumentspro’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39python39.zip’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39DLLs’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39lib’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39’, ‘C:UsersukfleAppDataRoamingPythonPython39site-packages’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39libsite-packages’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39libsite-packageswin32’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39libsite-packageswin32lib’, ‘C:UsersukfleAppDataLocalProgramsPythonPython39libsite-packagesPythonwin’] Server time: Wed, 19 May 2021 14:05:40 +0000

How to solve it? Or what to use in place of DO_NOTHING? You can also use OneToOneField if you want to solve this problem. Thank you 🙂

Advertisement

Answer

Check options under on_delete argument in this link. You can use the SET_NULL option which sets the data as NULL but as described the field should nullable. DO_NOTHING is the worst thing you can do because when a deletion occurs the data stays as it is and there becomes an object that does not exist.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement