Django

Code

Ticket #3182: update_or_create.diff

File update_or_create.diff, 1.4 kB (added by Gary Wilson <gary.wilson@gmail.com>, 3 years ago)

update_or_create() methods for QuerySet? and Manager

  • django/db/models/manager.py

    old new  
    6868 
    6969    def get_or_create(self, **kwargs): 
    7070        return self.get_query_set().get_or_create(**kwargs) 
    71          
     71 
     72    def update_or_create(self, **kwargs): 
     73        return self.get_query_set().update_or_create(**kwargs) 
     74 
    7275    def create(self, **kwargs): 
    7376        return self.get_query_set().create(**kwargs) 
    7477 
  • django/db/models/query.py

    old new  
    240240            obj.save() 
    241241            return obj, True 
    242242 
     243    def update_or_create(self, **kwargs): 
     244        """ 
     245        Looks up an object with the given kwargs, creating one if necessary. 
     246        If the object already exists, then its fields are updated with the 
     247        values passed in the defaults dictionary. 
     248        Returns a tuple of (object, created), where created is a boolean 
     249        specifying whether an object was created. 
     250        """ 
     251        obj, created = self.get_or_create(**kwargs) 
     252        if not created: 
     253            obj.update(**kwargs.pop('defaults', {})) 
     254        return obj, created 
     255 
    243256    def latest(self, field_name=None): 
    244257        """ 
    245258        Returns the latest object, according to the model's 'get_latest_by'