我创建了UserProfile
(从用户扩展)并写入settings.py
AUTH_PROFILE_MODULE = 'mainapp.UserProfile'.
当我删除UserProfile
(来自管理区域)时,我也会删除User
项。
我尝试删除用户self.user.delete()
,但方法删除(在UserProfile中)不调用。为什么?
这是我的代码:
class UserProfile(models.Model):
avatar = models.ImageField(upload_to = settings.PATH_AVATARS, blank=True)
url = models.URLField(blank=True)
user = models.OneToOneField(User)
def __unicode__(self):
return self.user.username
def delete(self, *args, **kwargs):
self.user.delete()
super(UserProfile, self).delete(*args, **kwargs)
答案 0 :(得分:11)
首先,回答为什么不从管理员调用“delete()”。这句话是:
尽管如此,_delete signals得到了很好的支持。以下是如何使用它:
from django.db.models import signals
def delete_user(sender, instance=None, **kwargs):
try:
instance.user
except User.DoesNotExist:
pass
else:
instance.user.delete()
signals.post_delete.connect(delete_user, sender=UserProfile)
这是我测试它的方式:
In [1]: from django.contrib.auth.models import User; from testapp.models import UserProfile; User.objects.all().delete(); UserProfile.objects.all().delete()
In [2]: user=User(username='foo'); user.save()
In [3]: profile=UserProfile(user=user); profile.save()
In [4]: UserProfile.objects.all().delete()
In [5]: User.objects.all()
Out[5]: []
当然,当调用对象的delete()方法时,这也有效:
In [1]: from django.contrib.auth.models import User; from testapp.models import UserProfile; User.objects.all().delete(); UserProfile.objects.all().delete()
In [2]: user=User(username='foo'); user.save()
In [3]: profile=UserProfile(user=user); profile.save()
In [4]: profile.delete()
In [5]: User.objects.all()
Out[5]: []
请注意,由于cascade delete,这有两种方式:
In [1]: from django.contrib.auth.models import User; from testapp.models import UserProfile; User.objects.all().delete(); UserProfile.objects.all().delete()
In [2]: user=User(username='foo'); user.save()
In [3]: profile=UserProfile(user=user); profile.save()
In [4]: user.delete()
In [5]: User.objects.all()
Out[5]: []
In [6]: UserProfile.objects.all()
Out[6]: []
如果您需要了解有关信号的更多信息,请参阅Django's extensive documentation。