我想获取依赖于(具有外键)特定auth_user
(用户模型)的所有 django 模型
这个的 SQL 版本看起来是 something like this但该示例并不像我希望的那样递归。
理想情况下,我想删除与特定用户
相关的数据而不破坏该用户,例如触发级联删除但跳过根对象的删除,在本例中为用户。
最佳答案
您可以为用户模型定义所有外键或 M2M key 的 lated_name
,如下所示:
# you models.py
class SomeModel(models.Model):
name = models.CharField(...)
user = models.ForeignKey(related_name='userrelated__somemodel')
# views.py
# you can get all dependence names of user model attributes
all_user_attrs = dir(request.user)
# ['userrelated__somemodel1', 'userrelated__somemodel2', ...]
# and here you can get all names only related fields
related_fields = filter(lambda x: 'userrelated__' in x, all_user_attrs)
# and if you want to get this field, you can do this:
for attr_name in related_fields:
attr = getattr(request.user, attr_name, None)
print attr
关于python - 获取 auth_user 的所有 Django 级联依赖模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21819048/