views:

444

answers:

3

I am using Django admin for managing my data. I have a Users, Groups and Domains tables Users table has many to many relationship with Groups and Domains tables. Domains table has one to many relationship with Groups table. and when I save the User data through admin I also need some addtional database updates in the users_group and the users_domains table. How do I do this? Where do I put the code. Thanks.

+2  A: 

I think you are looking for InlineModels. They allow you to edit related models in the same page as the parent model. If you are looking for greater control than this, you can override the ModelAdmin save methods.

Also, always check out the Manual when you need something. It really is quite good.

Paolo Bergantino
Paolo:Looks like I need to override the save method.As I mentioned before I need to update a couple of database tables... and let rest of the operations perform as usual. How do I do that.Thanks
Look in the example in the documentation. Just define a function named save_model in the AdminModel class and do what you need in there.
Paolo Bergantino
I was just playing around with save_model.Looks like whatever statements put in here are executed and the save operation follows even if I do not explicitly call save(). Is this the right behavior. I am not able to find any further documentation on the django website. Thanks.
This is the right behavior. Are you trying to abort the save or something? I do not think that is possible without some hacking around.
Paolo Bergantino
When I save the save_model is executed before the POST and the GET. Is there a way to execute the save_model after the POST and before the GET.
A: 

Paolo: Looks like I need to override the save method. As I mentioned before I need to update a couple of database tables... and let rest of the operations perform as usual. How do I do that. Thanks

You were right to comment on my answer first. The way this site is set up we try to avoid adding answers that are in fact comments.
Paolo Bergantino
A: 

The best way to update other database tables is to perform the necessary get and save operations. However, if you have a many-to-many relationship, by default, both sides of the relationship are accessible from a _set parameter. That is, user.group_set.all() will give you all Group objects associated with a user, while group.user_set.all() will give you all User objects associated with a group. So if you override the save method (or register a signal listener--whichever option sounds stylistically more pleasing), try:

for group in user.group_set.all():
    #play with group object
    ....
    group.save()
David Berger