Login

Snippets by abhin4v

Snippet List

update_or_create

Django provides a `get_or_create` helper method in the `models.Manager` class which looks up an object for the given `kwargs`, creating one if necessary. But sometime you need a method which updates the object with given `kwargs` or creates it if it's not found. This snippet provides the helper for that purpose. Use the snippet like this: from django.db import models class PersonManager(models.Manager): update_or_create = _update_or_create class Person(models.Model): first_name = models.CharField() last_name = models.CharField() city = models.CharField() objects = PersonManager() person, created, updated = Person.objects.update_or_create(first_name="John", last_name="Smith", defaults=dict(city="London")) The method returns a tuple of (`object`, `created`, `updated`), where `created` and `updated` are booleans specifying whether an `object` was created or updated respectively. Both `created` and `updated` are `false` if `object` is neither created nor updated (that is `object` has just been fetched "as is" from db). This happens if the update fails.

  • model
  • helper
  • update
  • create
Read More

abhin4v has posted 1 snippet.