how to use update_or_create


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


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

:three: by using update_or_create is able to create new entries (:smile:). But, on the time of edit, it creates new entry (:confused:). I know that , method update_or_create need some unique entity (an id for instance) which _view _or JS’s fetch can’t generate :man_cook: while creating new object :green_circle: … what unique value can go inside _update_orcreate method ?

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

When you call 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.)