# how to use update\_or\_create

**URL:** https://forum.djangoproject.com/t/how-to-use-update-or-create/5792
**Category:** Using Django
**Created:** [December 22, 2020, 12:15am UTC](https://forum.djangoproject.com/t/how-to-use-update-or-create/5792 "2020-12-22T00:15:14Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![PRA1995SAG](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pra1995sag/32/2207_2.png) [@PRA1995SAG](https://forum.djangoproject.com/u/PRA1995SAG)
#### Post date: [December 22, 2020, 12:15am UTC](https://forum.djangoproject.com/t/how-to-use-update-or-create/5792/1 "2020-12-22T00:15:14Z")

</div>

> 1️⃣ `models.py`

```py
class Post(models.Model):
    poster = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField(max_length=500)
    timestamp = models.DateTimeField(default=timezone.now)
    likes = models.ManyToManyField(User, blank=True, related_name='likes')

```

> 2️⃣ `views.py`

```py
def index(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        # postid = data.get('postid', '')
        postcontent = data.get('postcontent', '')
        print(postcontent)
        obj, created = Post.objects.update_or_create(
            poster=request.user, content=postcontent, 
            defaults={'content': postcontent})

```

> 3️⃣ by using _update\_or\_create_ `views.py` is able to create new entries (😄). But, on the time of `edit`, it creates `new` entry (😕). I know that , method _update\_or\_create_ need some unique entity (an `id` for instance) which \_view \_or _JS’s fetch_ can’t generate 👨‍🍳 while creating new `object` 🟢 … what `unique` value can go inside \_update\_orcreate method ?

---

<div class="post-metadata">

### Author: ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)
#### Post date: [December 22, 2020, 1:07am UTC](https://forum.djangoproject.com/t/how-to-use-update-or-create/5792/2 "2020-12-22T01:07:52Z")

</div>

I’m sorry, I’m not following what you’re trying to ask here.

When you call [update\_or\_create](https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.update_or_create), Django will search for an existing instance that satisfies the search criteria given. If no such instance is found, it will create a new instance with the values given in the `defaults` dict.

So using your snippet as an example, Django is going to look for an existing object where `poster=request.user` and `content=postcontent`. If it doesn’t already find one matching those criteria, it will create a new Post object, with `content = postcontent`. (Notice, however, you’re not setting the `poster` when you do this.)
