我在我的处理程序中放置了一个断点:
def handle_user_save(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
EmailNotifications.objects.create(user=instance)
else:
import pdb;pdb.set_trace()
post_save.connect(handler_user_save, sender=User)
在pdb中:
(Pdb) dir(instance)
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_base_manager', '_default_manager', '_deferred', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_set_pk_val', '_state', 'addressbookentry_set', 'blogcomment_set', 'blogentry_set', 'check_password', 'clean', 'clean_fields', 'date_error_message', 'date_joined', 'delete', 'email', 'email_user', 'emailnotifications', 'first_name', 'full_clean', 'get_absolute_url', 'get_all_permissions', 'get_full_name', 'get_group_permissions', 'get_next_by_date_joined', 'get_next_by_last_login', 'get_previous_by_date_joined', 'get_previous_by_last_login', 'get_profile', 'groups', 'has_module_perms', 'has_perm', 'has_perms', 'has_usable_password', 'id', 'is_active', 'is_anonymous', 'is_authenticated', 'is_staff', 'is_superuser', 'last_login', 'last_name', 'logentry_set', 'natural_key', 'objects', 'password', 'pk', 'prepare_database_save', 'project_set', 'save', 'save_base', 'serializable_value', 'set_password', 'set_unusable_password', 'unique_error_message', 'user_permissions', 'username', 'userprofile', 'validate_unique', 'vote_set']
和
(Pdb) instance.groups.all()
[]
此时似乎没有显示更改。但这很可能是因为我正在进行数据库查询以获取组。是否还有其他地方可以拦截用户模型的更新?
或者其中一个实例字段可以给我答案?这些干净的方法/字段似乎都不包含任何有用的东西。
答案 0 :(得分:2)
由于User
和Group
之间的关系是ManyToManyField
,因此此关系中的修改会触发另一个信号:m2m_changed
。来自documentation:
在模型实例上更改ManyToManyField时发送。严格来说,这不是模型信号,因为它是由ManyToManyField发送的,但由于它在跟踪模型的更改时补充了pre_save / post_save和pre_delete / post_delete,因此它包含在此处。
因此,您可以检查特定用户的组是否已更改:
def handle_m2m_changed(sender, instance, action, **kwargs):
if action == 'post_add' or action == 'post_remove':
print instance.groups.all()
m2m_changed.connect(handle_m2m_changed, sender=User.groups.through)