0

I would like to get all django models that depend (has foreign key) on a particular auth_user (User model)

The SQL version of this would look something like this except that example isn't recursive as i would like to.

Ideally i would like to delete any related data to a particular User without destroying that User, like triggering the cascade-delete but skipping the deleting of the root object, in this example the user.

Community
  • 1
  • 1
Leo Gallucci
  • 16,355
  • 12
  • 77
  • 110

1 Answers1

1

You can define a related_name of all ForeignKeys or M2M keys to User model, like this:

# 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
freylis
  • 814
  • 6
  • 15
  • This looks good but I cannot change `related_name='userrelated__...` on every model, they are already set to other meaningful values and i would break the app. – Leo Gallucci Feb 17 '14 at 12:56
  • Also, you can get all default user method and attrs, and all methods and attrs from your project. Different is a Fkeys, m2m-keys and o2o keys :] – freylis Feb 17 '14 at 16:14