On Jan 15, 2010, at 4:22 PM, Victor Loureiro Lima wrote:

> Here is the deal:
> 
> class MyModel ( models.Model ):
>   title = models.CharField( max_length = 100 )
>   only_me = models.BooleanField( default = False )
> 
>  Question: Whats the proper way to guarantee that no matter how many 
> MyModel's are available in the database, only one of them
> will have the only_me set as True? To further clarify things: In the admin, 
> whenever I check the only_me checkbox, and save my model, all other models of 
> this class will have to have its own only_me field set to false.
> 
>  As far as I know, there is no other way of doing this unless I iterate over 
> all MyModel' s objects and uncheck them if they are checked, save them, then 
> afterwards check the model that I am actually saving setting the only_me 
> field to True.
> 
>  I tried doing this on the actual save() of the model, no success. Everytime 
> I called save on iterated objects, I, of course, got the maximum recursive 
> depth error thrown at me. 
>  Fair enough, I quickly thought about signals, hooking my function to 
> post_save(), however I inevitabilly stumbled upon the same
> problem: When I called save() on the iterated objects the post_save signal 
> got sent, I would step again in the same function, thus
> no cookie for me.
>  I jumped over to overriding AdminForm' s save() method, so that I would 
> iterate there on the models unchecking them if necessary, and them returning 
> the proper object, but I stopped that and I said to myself that I must be 
> doing something really stupid, so Im coming to you guys: What would the 
> propper way of doing this?
> 

    def save(self, force_insert=False, force_update=False):
        if self.only_me is True:
            # if this is the new default, set others to False
            MyModel.objects.exclude(pk=self.pk).update(only_me=False)
            
        super(MyModel, self).save(force_insert, force_update) # Call the "real" 
save() method.


--
Eric Chamberlain, Founder
RF.com - http://RF.com/







-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.


Reply via email to