Prevent delete in Django model

后端 未结 6 838
醉酒成梦
醉酒成梦 2020-12-30 01:08

I have a setup like this (simplified for this question):

class Employee(models.Model):
    name = models.CharField(name, unique=True)

class Project(models.M         


        
6条回答
  •  情话喂你
    2020-12-30 01:54

    I have a suggestion but I'm not sure it is any better than your current idea. Taking a look at the answer here for a distant but not unrelated problem, you can override in the django admin various actions by essentially deleting them and using your own. So, for example, where they have:

    def really_delete_selected(self, request, queryset):
        deleted = 0
        notdeleted = 0
        for obj in queryset:
            if obj.project_set.all().count() > 0:
                # set status to fail
                notdeleted = notdeleted + 1
                pass
            else:
                obj.delete()
                deleted = deleted + 1
        # ...
    

    If you're not using django admin like myself, then simply build that check into your UI logic before you allow the user to delete the object.

提交回复
热议问题