场景描述
采用OneToOneField 生成Users对象,当我们需要删除Users对象时,我希望联动删除User账户。
解决方案
class Users(models.Model):
user = models.OneToOneField(User,verbose_name=u'用户名',on_delete=models.DO_NOTHING)
user_name=models.CharField(_(u'人员姓名'),max_length=30)
user_type=models.ManyToManyField(UsersType,verbose_name=u'人员类型')
user_department=models.ForeignKey(Department, verbose_name=u'单位信息',on_delete=models.DO_NOTHING)
user_mobilephone=models.CharField(_(u'手机号码'), max_length=25,null=True,blank=True)
删除
def delete_models(self, queryset):
userList=[]
for obj in queryset:
UserWidget.objects.filter(user=obj.user).delete()
UserSettings.objects.filter(user=obj.user).delete()
userList.append(obj.user)
super(UsersAdmin, self).delete_models(queryset)
for item in userList:
item.delete()