Ticket #3182: update_or_create.diff

File update_or_create.diff, 1.4 KB (added by Gary Wilson <gary.wilson@…>, 18 years ago)

update_or_create() methods for QuerySet and Manager

  • django/db/models/manager.py

    === modified file 'django/db/models/manager.py'
     
    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

    === modified file 'django/db/models/query.py'
     
    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'
Back to Top